opencode-matrixx 2.6.6 → 2.6.8
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/agents/seraph.d.ts +1 -1
- package/dist/cli.js +51 -4
- package/dist/config/schema/background-task.d.ts +37 -0
- package/dist/config/schema/dcp.d.ts +46 -0
- package/dist/config/schema/matrixx-config.d.ts +32 -0
- package/dist/features/background-agent/admission.d.ts +24 -0
- package/dist/features/background-agent/concurrency.d.ts +9 -0
- package/dist/features/background-agent/constants.d.ts +13 -0
- package/dist/features/background-agent/handle-index.d.ts +12 -0
- package/dist/features/background-agent/manager.d.ts +59 -4
- package/dist/features/background-agent/notification-builder.d.ts +1 -0
- package/dist/features/background-agent/reconcile.d.ts +33 -0
- package/dist/features/background-agent/revive.d.ts +39 -0
- package/dist/features/background-agent/session-output.d.ts +40 -0
- package/dist/features/background-agent/task-history.d.ts +20 -0
- package/dist/features/background-agent/types.d.ts +21 -1
- package/dist/features/background-agent/wake-scheduler.d.ts +47 -0
- package/dist/features/background-agent/wallclock.d.ts +37 -0
- package/dist/features/bdd/schema.d.ts +5 -5
- package/dist/features/builtin-commands/templates/refactor.d.ts +1 -1
- package/dist/features/context-injector/collector.d.ts +2 -0
- package/dist/features/context-injector/index.d.ts +1 -1
- package/dist/hooks/agent-usage-reminder/constants.d.ts +1 -0
- package/dist/hooks/compaction-context-injector/hook.d.ts +1 -0
- package/dist/hooks/context-mode-enforcer/constants.d.ts +1 -1
- package/dist/hooks/task-continuation-enforcer/constants.d.ts +4 -0
- package/dist/index.js +2172 -1276
- package/dist/matrixx.schema.json +165 -3
- package/dist/plugin-handlers/agent-config-handler.d.ts +2 -1
- package/dist/shared/context-mode-enforcement.d.ts +35 -0
- package/dist/shared/index.d.ts +1 -1
- package/dist/shared/poll-timeout-outcome.d.ts +21 -0
- package/dist/shared/revive-outcome.d.ts +15 -0
- package/dist/shared/saturated-outcome.d.ts +18 -0
- package/dist/shared/wallclock-outcome.d.ts +18 -0
- package/dist/tools/background-task/constants.d.ts +1 -0
- package/dist/tools/background-task/create-background-revive.d.ts +3 -0
- package/dist/tools/background-task/index.d.ts +1 -1
- package/dist/tools/background-task/tools.d.ts +1 -0
- package/dist/tools/background-task/types.d.ts +9 -0
- package/dist/tools/dcp-switch-profile/tools.d.ts +7 -0
- package/dist/tools/delegate-task/constants.d.ts +1 -0
- package/dist/tools/index.d.ts +1 -2
- package/package.json +1 -1
- package/dist/shared/context-mode-prompt.d.ts +0 -12
- package/dist/tools/delegate-agent/background-executor.d.ts +0 -13
- package/dist/tools/delegate-agent/completion-poller.d.ts +0 -11
- package/dist/tools/delegate-agent/constants.d.ts +0 -2
- package/dist/tools/delegate-agent/index.d.ts +0 -3
- package/dist/tools/delegate-agent/message-dir.d.ts +0 -1
- package/dist/tools/delegate-agent/message-processor.d.ts +0 -2
- package/dist/tools/delegate-agent/session-creator.d.ts +0 -15
- package/dist/tools/delegate-agent/sync-executor.d.ts +0 -21
- package/dist/tools/delegate-agent/tools.d.ts +0 -3
- package/dist/tools/delegate-agent/types.d.ts +0 -19
- /package/dist/{shared/context-mode-prompt.test.d.ts → tools/delegate-task/poll-timeout-outcome.test.d.ts} +0 -0
|
@@ -1,4 +1,22 @@
|
|
|
1
1
|
import type { BackgroundTaskStatus } from "./types";
|
|
2
|
+
export type JobBoardStrategy = "latest" | "checkpoint-compatible";
|
|
3
|
+
export interface JobBoardRow {
|
|
4
|
+
agent: string;
|
|
5
|
+
category?: string;
|
|
6
|
+
status: BackgroundTaskStatus;
|
|
7
|
+
description: string;
|
|
8
|
+
session?: string;
|
|
9
|
+
}
|
|
10
|
+
export interface JobBoardSnapshot {
|
|
11
|
+
strategy: JobBoardStrategy;
|
|
12
|
+
block: string;
|
|
13
|
+
retained?: string[];
|
|
14
|
+
}
|
|
15
|
+
export interface BuildJobBoardSnapshotOpts {
|
|
16
|
+
strategy?: JobBoardStrategy;
|
|
17
|
+
maxRetained?: number;
|
|
18
|
+
previous?: string[];
|
|
19
|
+
}
|
|
2
20
|
export interface TaskHistoryEntry {
|
|
3
21
|
id: string;
|
|
4
22
|
sessionID?: string;
|
|
@@ -15,4 +33,6 @@ export declare class TaskHistory {
|
|
|
15
33
|
getByParentSession(parentSessionID: string): TaskHistoryEntry[];
|
|
16
34
|
clearSession(parentSessionID: string): void;
|
|
17
35
|
formatForCompaction(parentSessionID: string): string | null;
|
|
36
|
+
getJobBoardEntries(parentSessionID: string): JobBoardRow[];
|
|
37
|
+
buildJobBoardSnapshot(parentSessionID: string, opts?: BuildJobBoardSnapshotOpts): JobBoardSnapshot | null;
|
|
18
38
|
}
|
|
@@ -1,4 +1,6 @@
|
|
|
1
|
-
export type BackgroundTaskStatus = "pending" | "running" | "completed" | "error" | "cancelled" | "interrupt";
|
|
1
|
+
export type BackgroundTaskStatus = "pending" | "running" | "completed" | "error" | "cancelled" | "interrupt" | "stopped" | "statusUncertain";
|
|
2
|
+
/** Why a background task reached a terminal state (persisted on the handle). */
|
|
3
|
+
export type BackgroundTerminalReason = "queue-saturated" | "no-output" | "uncertain" | "aborted" | "stale" | "nested-depth-exceeded" | "wall-clock-timeout";
|
|
2
4
|
export interface ToolCallWindow {
|
|
3
5
|
lastSignature: string;
|
|
4
6
|
consecutiveCount: number;
|
|
@@ -54,6 +56,10 @@ export interface BackgroundTask {
|
|
|
54
56
|
lastMsgCount?: number;
|
|
55
57
|
/** Number of consecutive polls with stable message count */
|
|
56
58
|
stablePolls?: number;
|
|
59
|
+
/** Why the task reached a terminal state (e.g. stopped/statusUncertain) */
|
|
60
|
+
terminalReason?: BackgroundTerminalReason;
|
|
61
|
+
/** Compressed result payload for handoff to parent session (set by tryCompleteTask) */
|
|
62
|
+
compactedResult?: string;
|
|
57
63
|
}
|
|
58
64
|
export interface LaunchInput {
|
|
59
65
|
description: string;
|
|
@@ -90,4 +96,18 @@ export interface ResumeInput {
|
|
|
90
96
|
parentAgent?: string;
|
|
91
97
|
parentTools?: Record<string, boolean>;
|
|
92
98
|
}
|
|
99
|
+
export interface ReviveInput {
|
|
100
|
+
taskId?: string;
|
|
101
|
+
sessionId?: string;
|
|
102
|
+
prompt: string;
|
|
103
|
+
parentSessionID: string;
|
|
104
|
+
parentMessageID: string;
|
|
105
|
+
parentModel?: {
|
|
106
|
+
providerID: string;
|
|
107
|
+
modelID: string;
|
|
108
|
+
};
|
|
109
|
+
parentAgent?: string;
|
|
110
|
+
parentTools?: Record<string, boolean>;
|
|
111
|
+
force?: boolean;
|
|
112
|
+
}
|
|
93
113
|
export {};
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
export interface WakeSchedulerConfig {
|
|
2
|
+
enabled?: boolean;
|
|
3
|
+
intervalMs?: number;
|
|
4
|
+
}
|
|
5
|
+
export interface WakeParentState {
|
|
6
|
+
hasPendingChildren: boolean;
|
|
7
|
+
hasUndeliveredNotifications: boolean;
|
|
8
|
+
hasUnfinishedTodos?: boolean;
|
|
9
|
+
}
|
|
10
|
+
export declare const WAKE_REMINDER_TEXT = "<system-reminder>\n[BACKGROUND WAKE]\n\nOne or more background tasks for this session are still running or have undelivered results.\nUse background_output with the task ID to retrieve results when ready.\nDo NOT poll - continue productive work.\n</system-reminder>";
|
|
11
|
+
export declare function isWakeSchedulerEnabled(cfg?: WakeSchedulerConfig): boolean;
|
|
12
|
+
export declare function resolveWakeIntervalMs(cfg?: WakeSchedulerConfig): number;
|
|
13
|
+
export declare function shouldWakeForParent(state: WakeParentState): boolean;
|
|
14
|
+
export declare function nextWakeDelay(lastWakeAtMs: number, intervalMs: number, nowMs?: number): number;
|
|
15
|
+
export declare class WakeTracker {
|
|
16
|
+
private stagnantByParent;
|
|
17
|
+
recordWake(parentSessionID: string, progressed: boolean): boolean;
|
|
18
|
+
resetOnActivity(parentSessionID: string): void;
|
|
19
|
+
stagnantCount(parentSessionID: string): number;
|
|
20
|
+
}
|
|
21
|
+
export type WakeTimerHandle = ReturnType<typeof setTimeout>;
|
|
22
|
+
export type WakeScheduleTimer = (callback: () => void, delayMs: number) => WakeTimerHandle;
|
|
23
|
+
export type WakeClearTimer = (handle: WakeTimerHandle) => void;
|
|
24
|
+
export interface WakeRegistration {
|
|
25
|
+
intervalMs: number;
|
|
26
|
+
readState: () => WakeParentState;
|
|
27
|
+
deliverWake: () => void | Promise<void>;
|
|
28
|
+
}
|
|
29
|
+
export declare class WakeScheduler {
|
|
30
|
+
private timers;
|
|
31
|
+
private registrations;
|
|
32
|
+
private snapshots;
|
|
33
|
+
private readonly tracker;
|
|
34
|
+
private readonly scheduleTimer;
|
|
35
|
+
private readonly clearTimer;
|
|
36
|
+
constructor(deps?: {
|
|
37
|
+
scheduleTimer?: WakeScheduleTimer;
|
|
38
|
+
clearTimer?: WakeClearTimer;
|
|
39
|
+
});
|
|
40
|
+
private armTimer;
|
|
41
|
+
schedule(parentSessionID: string, registration: WakeRegistration): void;
|
|
42
|
+
clear(parentSessionID: string): void;
|
|
43
|
+
dispose(): void;
|
|
44
|
+
hasScheduledWake(parentSessionID: string): boolean;
|
|
45
|
+
private clearTimerFor;
|
|
46
|
+
private tick;
|
|
47
|
+
}
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Wall-clock supervisor: fire-once elapsed-time bound for running background tasks.
|
|
3
|
+
*
|
|
4
|
+
* Staleness is activity-based; this module is elapsed-time-based. Each armed entry
|
|
5
|
+
* fires its callback exactly once when `startedAtMs + timeoutMs` passes, no matter
|
|
6
|
+
* how busy or productive the task looks. A timeout of `0` or `undefined` means OFF
|
|
7
|
+
* and arms nothing.
|
|
8
|
+
*
|
|
9
|
+
* Grace contract (manager-owned, pinned here): on fire the manager aborts the
|
|
10
|
+
* session once, waits `wallClockAbortGraceMs`, then marks the task terminal —
|
|
11
|
+
* unless the task completed naturally during grace, in which case the natural
|
|
12
|
+
* outcome wins and the pending mark is cancelled.
|
|
13
|
+
*
|
|
14
|
+
* This module must not import from manager/client/fs — pure timers only. It mirrors
|
|
15
|
+
* the settled-flag lifecycle of `acquireWithDeadline` in `concurrency.ts`.
|
|
16
|
+
*/
|
|
17
|
+
/** Maximum delay accepted by `setTimeout` (2^31-1 ms); enforced by schema max too. */
|
|
18
|
+
export declare const MAX_WALLCLOCK_TIMEOUT_MS = 2147483647;
|
|
19
|
+
/** Context delivered to the fire callback exactly once per armed deadline. */
|
|
20
|
+
export interface WallclockFireContext {
|
|
21
|
+
taskId: string;
|
|
22
|
+
elapsedMs: number;
|
|
23
|
+
limitMs: number;
|
|
24
|
+
}
|
|
25
|
+
export type WallclockFireCallback = (ctx: WallclockFireContext) => void;
|
|
26
|
+
/** Pure remaining-time math: deadline minus now (negative when already expired). */
|
|
27
|
+
export declare function remainingMs(startedAtMs: number, timeoutMs: number, nowMs?: number): number;
|
|
28
|
+
/** OFF (`0`/`undefined`) never arms; any other value is an active elapsed-time bound. */
|
|
29
|
+
export declare function isWallclockEnabled(timeoutMs: number | undefined): timeoutMs is number;
|
|
30
|
+
export declare class WallclockSupervisor {
|
|
31
|
+
private entries;
|
|
32
|
+
arm(taskId: string, startedAtMs: number, timeoutMs: number | undefined, onFire: WallclockFireCallback): void;
|
|
33
|
+
disarm(taskId: string): boolean;
|
|
34
|
+
disarmAll(): void;
|
|
35
|
+
size(): number;
|
|
36
|
+
getDeadlineAt(taskId: string): number | undefined;
|
|
37
|
+
}
|
|
@@ -86,8 +86,8 @@ export declare const HttpMethodSchema: z.ZodEnum<{
|
|
|
86
86
|
}>;
|
|
87
87
|
export declare const ResponseFormatSchema: z.ZodEnum<{
|
|
88
88
|
binary: "binary";
|
|
89
|
-
json: "json";
|
|
90
89
|
text: "text";
|
|
90
|
+
json: "json";
|
|
91
91
|
html: "html";
|
|
92
92
|
xml: "xml";
|
|
93
93
|
}>;
|
|
@@ -118,8 +118,8 @@ export declare const ApiResponseSchema: z.ZodObject<{
|
|
|
118
118
|
status: z.ZodNumber;
|
|
119
119
|
format: z.ZodEnum<{
|
|
120
120
|
binary: "binary";
|
|
121
|
-
json: "json";
|
|
122
121
|
text: "text";
|
|
122
|
+
json: "json";
|
|
123
123
|
html: "html";
|
|
124
124
|
xml: "xml";
|
|
125
125
|
}>;
|
|
@@ -174,8 +174,8 @@ export declare const ApiAnnotationsSchema: z.ZodObject<{
|
|
|
174
174
|
status: z.ZodNumber;
|
|
175
175
|
format: z.ZodEnum<{
|
|
176
176
|
binary: "binary";
|
|
177
|
-
json: "json";
|
|
178
177
|
text: "text";
|
|
178
|
+
json: "json";
|
|
179
179
|
html: "html";
|
|
180
180
|
xml: "xml";
|
|
181
181
|
}>;
|
|
@@ -236,8 +236,8 @@ export declare const ContractAnnotationsSchema: z.ZodObject<{
|
|
|
236
236
|
status: z.ZodNumber;
|
|
237
237
|
format: z.ZodEnum<{
|
|
238
238
|
binary: "binary";
|
|
239
|
-
json: "json";
|
|
240
239
|
text: "text";
|
|
240
|
+
json: "json";
|
|
241
241
|
html: "html";
|
|
242
242
|
xml: "xml";
|
|
243
243
|
}>;
|
|
@@ -366,8 +366,8 @@ export declare const ContractSchema: z.ZodObject<{
|
|
|
366
366
|
status: z.ZodNumber;
|
|
367
367
|
format: z.ZodEnum<{
|
|
368
368
|
binary: "binary";
|
|
369
|
-
json: "json";
|
|
370
369
|
text: "text";
|
|
370
|
+
json: "json";
|
|
371
371
|
html: "html";
|
|
372
372
|
xml: "xml";
|
|
373
373
|
}>;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
export declare const REFACTOR_TEMPLATE = "# Intelligent Refactor Command\n\n## Usage\n```\n/refactor <refactoring-target> [--scope=<file|module|project>] [--strategy=<safe|aggressive>]\n\nArguments:\n refactoring-target: What to refactor. Can be:\n - File path: src/auth/handler.ts\n - Symbol name: \"AuthService class\"\n - Pattern: \"all functions using deprecated API\"\n - Description: \"extract validation logic into separate module\"\n\nOptions:\n --scope: Refactoring scope (default: module)\n - file: Single file only\n - module: Module/directory scope\n - project: Entire codebase\n\n --strategy: Risk tolerance (default: safe)\n - safe: Conservative, maximum test coverage required\n - aggressive: Allow broader changes with adequate coverage\n```\n\n## What This Command Does\n\nPerforms intelligent, deterministic refactoring with full codebase awareness. Unlike blind search-and-replace, this command:\n\n1. **Understands your intent** - Analyzes what you actually want to achieve\n2. **Maps the codebase** - Builds a definitive codemap before touching anything\n3. **Assesses risk** - Evaluates test coverage and determines verification strategy\n4. **Plans meticulously** - Creates a detailed plan with Plan agent\n5. **Executes precisely** - Step-by-step refactoring with LSP and AST-grep\n6. **Verifies constantly** - Runs tests after each change to ensure zero regression\n\n---\n\n# PHASE 0: INTENT GATE (MANDATORY FIRST STEP)\n\n**BEFORE ANY ACTION, classify and validate the request.**\n\n## Step 0.1: Parse Request Type\n\n| Signal | Classification | Action |\n|--------|----------------|--------|\n| Specific file/symbol | Explicit | Proceed to codebase analysis |\n| \"Refactor X to Y\" | Clear transformation | Proceed to codebase analysis |\n| \"Improve\", \"Clean up\" | Open-ended | **MUST ask**: \"What specific improvement?\" |\n| Ambiguous scope | Uncertain | **MUST ask**: \"Which modules/files?\" |\n| Missing context | Incomplete | **MUST ask**: \"What's the desired outcome?\" |\n\n## Step 0.2: Validate Understanding\n\nBefore proceeding, confirm:\n- [ ] Target is clearly identified\n- [ ] Desired outcome is understood\n- [ ] Scope is defined (file/module/project)\n- [ ] Success criteria can be articulated\n\n**If ANY of above is unclear, ASK CLARIFYING QUESTION:**\n\n```\nI want to make sure I understand the refactoring goal correctly.\n\n**What I understood**: [interpretation]\n**What I'm unsure about**: [specific ambiguity]\n\nOptions I see:\n1. [Option A] - [implications]\n2. [Option B] - [implications]\n\n**My recommendation**: [suggestion with reasoning]\n\nShould I proceed with [recommendation], or would you prefer differently?\n```\n\n## Step 0.3: Create Initial Todos\n\n**IMMEDIATELY after understanding the request, create todos:**\n\n```\nTodoWrite([\n {\"id\": \"phase-1\", \"content\": \"PHASE 1: Codebase Analysis - launch parallel explore agents\", \"status\": \"pending\", \"priority\": \"high\"},\n {\"id\": \"phase-2\", \"content\": \"PHASE 2: Build Codemap - map dependencies and impact zones\", \"status\": \"pending\", \"priority\": \"high\"},\n {\"id\": \"phase-3\", \"content\": \"PHASE 3: Test Assessment - analyze test coverage and verification strategy\", \"status\": \"pending\", \"priority\": \"high\"},\n {\"id\": \"phase-4\", \"content\": \"PHASE 4: Plan Generation - invoke Plan agent for detailed refactoring plan\", \"status\": \"pending\", \"priority\": \"high\"},\n {\"id\": \"phase-5\", \"content\": \"PHASE 5: Execute Refactoring - step-by-step with continuous verification\", \"status\": \"pending\", \"priority\": \"high\"},\n {\"id\": \"phase-6\", \"content\": \"PHASE 6: Final Verification - full test suite and regression check\", \"status\": \"pending\", \"priority\": \"high\"}\n])\n```\n\n---\n\n# PHASE 1: CODEBASE ANALYSIS (PARALLEL EXPLORATION)\n\n**Mark phase-1 as in_progress.**\n\n## 1.1: Launch Parallel Explore Agents (BACKGROUND)\n\nFire ALL of these simultaneously using `delegate_agent`:\n\n```\n// Agent 1: Find the refactoring target\ndelegate_agent(\n subagent_type=\"trinity\",\n run_in_background=true,\n prompt=\"Find all occurrences and definitions of [TARGET]. \n Report: file paths, line numbers, usage patterns.\"\n)\n\n// Agent 2: Find related code\ndelegate_agent(\n subagent_type=\"trinity\", \n run_in_background=true,\n prompt=\"Find all code that imports, uses, or depends on [TARGET].\n Report: dependency chains, import graphs.\"\n)\n\n// Agent 3: Find similar patterns\ndelegate_agent(\n subagent_type=\"trinity\",\n run_in_background=true,\n prompt=\"Find similar code patterns to [TARGET] in the codebase.\n Report: analogous implementations, established conventions.\"\n)\n\n// Agent 4: Find tests\ndelegate_agent(\n subagent_type=\"trinity\",\n run_in_background=true,\n prompt=\"Find all test files related to [TARGET].\n Report: test file paths, test case names, coverage indicators.\"\n)\n\n// Agent 5: Architecture context\ndelegate_agent(\n subagent_type=\"trinity\",\n run_in_background=true,\n prompt=\"Find architectural patterns and module organization around [TARGET].\n Report: module boundaries, layer structure, design patterns in use.\"\n)\n```\n\n## 1.2: Direct Tool Exploration (WHILE AGENTS RUN)\n\nWhile background agents are running, use direct tools:\n\n### LSP Tools for Precise Analysis:\n\n```typescript\n// Find definition(s)\nLspGotoDefinition(filePath, line, character) // Where is it defined?\n\n// Find ALL usages across workspace\nLspFindReferences(filePath, line, character, includeDeclaration=true)\n\n// Get file structure\nLspDocumentSymbols(filePath) // Hierarchical outline\nLspWorkspaceSymbols(filePath, query=\"[target_symbol]\") // Search by name\n\n// Get current diagnostics\nlsp_diagnostics(filePath) // Errors, warnings before we start\n```\n\n### AST-Grep for Pattern Analysis:\n\n```typescript\n// Find structural patterns\nast_grep_search(\n pattern=\"function $NAME($$$) { $$$ }\", // or relevant pattern\n lang=\"typescript\", // or relevant language\n paths=[\"src/\"]\n)\n\n// Preview refactoring (DRY RUN)\nast_grep_replace(\n pattern=\"[old_pattern]\",\n rewrite=\"[new_pattern]\",\n lang=\"[language]\",\n dryRun=true // ALWAYS preview first\n)\n```\n\n### Grep for Text Patterns:\n\n```\ngrep(pattern=\"[search_term]\", path=\"src/\", include=\"*.ts\")\n```\n\n## 1.3: Collect Background Results\n\n```\nbackground_output(task_id=\"[agent_1_id]\")\nbackground_output(task_id=\"[agent_2_id]\")\n...\n```\n\n**Mark phase-1 as completed after all results collected.**\n\n---\n\n# PHASE 2: BUILD CODEMAP (DEPENDENCY MAPPING)\n\n**Mark phase-2 as in_progress.**\n\n## 2.1: Construct Definitive Codemap\n\nBased on Phase 1 results, build:\n\n```\n## CODEMAP: [TARGET]\n\n### Core Files (Direct Impact)\n- `path/to/file.ts:L10-L50` - Primary definition\n- `path/to/file2.ts:L25` - Key usage\n\n### Dependency Graph\n```\n[TARGET] \n\u251C\u2500\u2500 imports from: \n\u2502 \u251C\u2500\u2500 module-a (types)\n\u2502 \u2514\u2500\u2500 module-b (utils)\n\u251C\u2500\u2500 imported by:\n\u2502 \u251C\u2500\u2500 consumer-1.ts\n\u2502 \u251C\u2500\u2500 consumer-2.ts\n\u2502 \u2514\u2500\u2500 consumer-3.ts\n\u2514\u2500\u2500 used by:\n \u251C\u2500\u2500 handler.ts (direct call)\n \u2514\u2500\u2500 service.ts (dependency injection)\n```\n\n### Impact Zones\n| Zone | Risk Level | Files Affected | Test Coverage |\n|------|------------|----------------|---------------|\n| Core | HIGH | 3 files | 85% covered |\n| Consumers | MEDIUM | 8 files | 70% covered |\n| Edge | LOW | 2 files | 50% covered |\n\n### Established Patterns\n- Pattern A: [description] - used in N places\n- Pattern B: [description] - established convention\n```\n\n## 2.2: Identify Refactoring Constraints\n\nBased on codemap:\n- **MUST follow**: [existing patterns identified]\n- **MUST NOT break**: [critical dependencies]\n- **Safe to change**: [isolated code zones]\n- **Requires migration**: [breaking changes impact]\n\n**Mark phase-2 as completed.**\n\n---\n\n# PHASE 3: TEST ASSESSMENT (VERIFICATION STRATEGY)\n\n**Mark phase-3 as in_progress.**\n\n## 3.1: Detect Test Infrastructure\n\n```bash\n# Check for test commands\ncat package.json | jq '.scripts | keys[] | select(test(\"test\"))'\n\n# Or for Python\nls -la pytest.ini pyproject.toml setup.cfg\n\n# Or for Go\nls -la *_test.go\n```\n\n## 3.2: Analyze Test Coverage\n\n```\n// Find all tests related to target\ndelegate_agent(\n subagent_type=\"trinity\",\n run_in_background=false, // Need this synchronously\n prompt=\"Analyze test coverage for [TARGET]:\n 1. Which test files cover this code?\n 2. What test cases exist?\n 3. Are there integration tests?\n 4. What edge cases are tested?\n 5. Estimated coverage percentage?\"\n)\n```\n\n## 3.3: Determine Verification Strategy\n\nBased on test analysis:\n\n| Coverage Level | Strategy |\n|----------------|----------|\n| HIGH (>80%) | Run existing tests after each step |\n| MEDIUM (50-80%) | Run tests + add safety assertions |\n| LOW (<50%) | **PAUSE**: Propose adding tests first |\n| NONE | **BLOCK**: Refuse aggressive refactoring |\n\n**If coverage is LOW or NONE, ask user:**\n\n```\nTest coverage for [TARGET] is [LEVEL].\n\n**Risk Assessment**: Refactoring without adequate tests is dangerous.\n\nOptions:\n1. Add tests first, then refactor (RECOMMENDED)\n2. Proceed with extra caution, manual verification required\n3. Abort refactoring\n\nWhich approach do you prefer?\n```\n\n## 3.4: Document Verification Plan\n\n```\n## VERIFICATION PLAN\n\n### Test Commands\n- Unit: `bun test` / `npm test` / `pytest` / etc.\n- Integration: [command if exists]\n- Type check: `tsc --noEmit` / `pyright` / etc.\n\n### Verification Checkpoints\nAfter each refactoring step:\n1. lsp_diagnostics \u2192 zero new errors\n2. Run test command \u2192 all pass\n3. Type check \u2192 clean\n\n### Regression Indicators\n- [Specific test that must pass]\n- [Behavior that must be preserved]\n- [API contract that must not change]\n```\n\n**Mark phase-3 as completed.**\n\n---\n\n# PHASE 4: PLAN GENERATION (PLAN AGENT)\n\n**Mark phase-4 as in_progress.**\n\n## 4.1: Invoke Plan Agent\n\n```\nTask(\n subagent_type=\"plan\",\n prompt=\"Create a detailed refactoring plan:\n\n ## Refactoring Goal\n [User's original request]\n\n ## Codemap (from Phase 2)\n [Insert codemap here]\n\n ## Test Coverage (from Phase 3)\n [Insert verification plan here]\n\n ## Constraints\n - MUST follow existing patterns: [list]\n - MUST NOT break: [critical paths]\n - MUST run tests after each step\n\n ## Requirements\n 1. Break down into atomic refactoring steps\n 2. Each step must be independently verifiable\n 3. Order steps by dependency (what must happen first)\n 4. Specify exact files and line ranges for each step\n 5. Include rollback strategy for each step\n 6. Define commit checkpoints\"\n)\n```\n\n## 4.2: Review and Validate Plan\n\nAfter receiving plan from Plan agent:\n\n1. **Verify completeness**: All identified files addressed?\n2. **Verify safety**: Each step reversible?\n3. **Verify order**: Dependencies respected?\n4. **Verify verification**: Test commands specified?\n\n## 4.3: Register Detailed Todos\n\nConvert Plan agent output into granular todos:\n\n```\nTodoWrite([\n // Each step from the plan becomes a todo\n {\"id\": \"refactor-1\", \"content\": \"Step 1: [description]\", \"status\": \"pending\", \"priority\": \"high\"},\n {\"id\": \"verify-1\", \"content\": \"Verify Step 1: run tests\", \"status\": \"pending\", \"priority\": \"high\"},\n {\"id\": \"refactor-2\", \"content\": \"Step 2: [description]\", \"status\": \"pending\", \"priority\": \"medium\"},\n {\"id\": \"verify-2\", \"content\": \"Verify Step 2: run tests\", \"status\": \"pending\", \"priority\": \"medium\"},\n // ... continue for all steps\n])\n```\n\n**Mark phase-4 as completed.**\n\n---\n\n# PHASE 5: EXECUTE REFACTORING (DETERMINISTIC EXECUTION)\n\n**Mark phase-5 as in_progress.**\n\n## 5.1: Execution Protocol\n\nFor EACH refactoring step:\n\n### Pre-Step\n1. Mark step todo as `in_progress`\n2. Read current file state\n3. Verify lsp_diagnostics is baseline\n\n### Execute Step\nUse appropriate tool:\n\n**For Symbol Renames:**\n```typescript\nlsp_prepare_rename(filePath, line, character) // Validate rename is possible\nlsp_rename(filePath, line, character, newName) // Execute rename\n```\n\n**For Pattern Transformations:**\n```typescript\n// Preview first\nast_grep_replace(pattern, rewrite, lang, dryRun=true)\n\n// If preview looks good, execute\nast_grep_replace(pattern, rewrite, lang, dryRun=false)\n```\n\n**For Structural Changes:**\n```typescript\n// Use Edit tool for precise changes\nedit(filePath, oldString, newString)\n```\n\n### Post-Step Verification (MANDATORY)\n\n```typescript\n// 1. Check diagnostics\nlsp_diagnostics(filePath) // Must be clean or same as baseline\n\n// 2. Run tests\nbash(\"bun test\") // Or appropriate test command\n\n// 3. Type check\nbash(\"tsc --noEmit\") // Or appropriate type check\n```\n\n### Step Completion\n1. If verification passes \u2192 Mark step todo as `completed`\n2. If verification fails \u2192 **STOP AND FIX**\n\n## 5.2: Failure Recovery Protocol\n\nIf ANY verification fails:\n\n1. **STOP** immediately\n2. **REVERT** the failed change\n3. **DIAGNOSE** what went wrong\n4. **OPTIONS**:\n - Fix the issue and retry\n - Skip this step (if optional)\n - Consult oracle agent for help\n - Ask user for guidance\n\n**NEVER proceed to next step with broken tests.**\n\n## 5.3: Commit Checkpoints\n\nAfter each logical group of changes:\n\n```bash\ngit add [changed-files]\ngit commit -m \"refactor(scope): description\n\n[details of what was changed and why]\"\n```\n\n**Mark phase-5 as completed when all refactoring steps done.**\n\n---\n\n# PHASE 6: FINAL VERIFICATION (REGRESSION CHECK)\n\n**Mark phase-6 as in_progress.**\n\n## 6.1: Full Test Suite\n\n```bash\n# Run complete test suite\nbun test # or npm test, pytest, go test, etc.\n```\n\n## 6.2: Type Check\n\n```bash\n# Full type check\ntsc --noEmit # or equivalent\n```\n\n## 6.3: Lint Check\n\n```bash\n# Run linter\neslint . # or equivalent\n```\n\n## 6.4: Build Verification (if applicable)\n\n```bash\n# Ensure build still works\nbun run build # or npm run build, etc.\n```\n\n## 6.5: Final Diagnostics\n\n```typescript\n// Check all changed files\nfor (file of changedFiles) {\n lsp_diagnostics(file) // Must all be clean\n}\n```\n\n## 6.6: Generate Summary\n\n```markdown\n## Refactoring Complete\n\n### What Changed\n- [List of changes made]\n\n### Files Modified\n- `path/to/file.ts` - [what changed]\n- `path/to/file2.ts` - [what changed]\n\n### Verification Results\n- Tests: PASSED (X/Y passing)\n- Type Check: CLEAN\n- Lint: CLEAN\n- Build: SUCCESS\n\n### No Regressions Detected\nAll existing tests pass. No new errors introduced.\n```\n\n**Mark phase-6 as completed.**\n\n---\n\n# CRITICAL RULES\n\n## NEVER DO\n- Skip lsp_diagnostics check after changes\n- Proceed with failing tests\n- Make changes without understanding impact\n- Use `as any`, `@ts-ignore`, `@ts-expect-error`\n- Delete tests to make them pass\n- Commit broken code\n- Refactor without understanding existing patterns\n\n## ALWAYS DO\n- Understand before changing\n- Preview before applying (ast_grep dryRun=true)\n- Verify after every change\n- Follow existing codebase patterns\n- Keep todos updated in real-time\n- Commit at logical checkpoints\n- Report issues immediately\n\n## ABORT CONDITIONS\nIf any of these occur, **STOP and consult user**:\n- Test coverage is zero for target code\n- Changes would break public API\n- Refactoring scope is unclear\n- 3 consecutive verification failures\n- User-defined constraints violated\n\n---\n\n# Tool Usage Philosophy\n\nYou already know these tools. Use them intelligently:\n\n## LSP Tools\nLeverage LSP tools for precision analysis. Key patterns:\n- **Understand before changing**: `LspGotoDefinition` to grasp context\n- **Impact analysis**: `LspFindReferences` to map all usages before modification\n- **Safe refactoring**: `lsp_prepare_rename` \u2192 `lsp_rename` for symbol renames\n- **Continuous verification**: `lsp_diagnostics` after every change\n\n## AST-Grep\nUse `ast_grep_search` and `ast_grep_replace` for structural transformations.\n**Critical**: Always `dryRun=true` first, review, then execute.\n\n## Agents\n- `explore`: Parallel codebase pattern discovery\n- `plan`: Detailed refactoring plan generation\n- `oracle`: Read-only consultation for complex architectural decisions and debugging\n- `librarian`: **Use proactively** when encountering deprecated methods or library migration tasks. Query official docs and OSS examples for modern replacements.\n\n## Deprecated Code & Library Migration\nWhen you encounter deprecated methods/APIs during refactoring:\n1. Fire `librarian` to find the recommended modern alternative\n2. **DO NOT auto-upgrade to latest version** unless user explicitly requests migration\n3. If user requests library migration, use `librarian` to fetch latest API docs before making changes\n\n---\n\n**Remember: Refactoring without tests is reckless. Refactoring without understanding is destructive. This command ensures you do neither.**\n\n<user-request>\n$ARGUMENTS\n</user-request>\n";
|
|
1
|
+
export declare const REFACTOR_TEMPLATE = "# Intelligent Refactor Command\n\n## Usage\n```\n/refactor <refactoring-target> [--scope=<file|module|project>] [--strategy=<safe|aggressive>]\n\nArguments:\n refactoring-target: What to refactor. Can be:\n - File path: src/auth/handler.ts\n - Symbol name: \"AuthService class\"\n - Pattern: \"all functions using deprecated API\"\n - Description: \"extract validation logic into separate module\"\n\nOptions:\n --scope: Refactoring scope (default: module)\n - file: Single file only\n - module: Module/directory scope\n - project: Entire codebase\n\n --strategy: Risk tolerance (default: safe)\n - safe: Conservative, maximum test coverage required\n - aggressive: Allow broader changes with adequate coverage\n```\n\n## What This Command Does\n\nPerforms intelligent, deterministic refactoring with full codebase awareness. Unlike blind search-and-replace, this command:\n\n1. **Understands your intent** - Analyzes what you actually want to achieve\n2. **Maps the codebase** - Builds a definitive codemap before touching anything\n3. **Assesses risk** - Evaluates test coverage and determines verification strategy\n4. **Plans meticulously** - Creates a detailed plan with Plan agent\n5. **Executes precisely** - Step-by-step refactoring with LSP and AST-grep\n6. **Verifies constantly** - Runs tests after each change to ensure zero regression\n\n---\n\n# PHASE 0: INTENT GATE (MANDATORY FIRST STEP)\n\n**BEFORE ANY ACTION, classify and validate the request.**\n\n## Step 0.1: Parse Request Type\n\n| Signal | Classification | Action |\n|--------|----------------|--------|\n| Specific file/symbol | Explicit | Proceed to codebase analysis |\n| \"Refactor X to Y\" | Clear transformation | Proceed to codebase analysis |\n| \"Improve\", \"Clean up\" | Open-ended | **MUST ask**: \"What specific improvement?\" |\n| Ambiguous scope | Uncertain | **MUST ask**: \"Which modules/files?\" |\n| Missing context | Incomplete | **MUST ask**: \"What's the desired outcome?\" |\n\n## Step 0.2: Validate Understanding\n\nBefore proceeding, confirm:\n- [ ] Target is clearly identified\n- [ ] Desired outcome is understood\n- [ ] Scope is defined (file/module/project)\n- [ ] Success criteria can be articulated\n\n**If ANY of above is unclear, ASK CLARIFYING QUESTION:**\n\n```\nI want to make sure I understand the refactoring goal correctly.\n\n**What I understood**: [interpretation]\n**What I'm unsure about**: [specific ambiguity]\n\nOptions I see:\n1. [Option A] - [implications]\n2. [Option B] - [implications]\n\n**My recommendation**: [suggestion with reasoning]\n\nShould I proceed with [recommendation], or would you prefer differently?\n```\n\n## Step 0.3: Create Initial Todos\n\n**IMMEDIATELY after understanding the request, create todos:**\n\n```\nTodoWrite([\n {\"id\": \"phase-1\", \"content\": \"PHASE 1: Codebase Analysis - launch parallel explore agents\", \"status\": \"pending\", \"priority\": \"high\"},\n {\"id\": \"phase-2\", \"content\": \"PHASE 2: Build Codemap - map dependencies and impact zones\", \"status\": \"pending\", \"priority\": \"high\"},\n {\"id\": \"phase-3\", \"content\": \"PHASE 3: Test Assessment - analyze test coverage and verification strategy\", \"status\": \"pending\", \"priority\": \"high\"},\n {\"id\": \"phase-4\", \"content\": \"PHASE 4: Plan Generation - invoke Plan agent for detailed refactoring plan\", \"status\": \"pending\", \"priority\": \"high\"},\n {\"id\": \"phase-5\", \"content\": \"PHASE 5: Execute Refactoring - step-by-step with continuous verification\", \"status\": \"pending\", \"priority\": \"high\"},\n {\"id\": \"phase-6\", \"content\": \"PHASE 6: Final Verification - full test suite and regression check\", \"status\": \"pending\", \"priority\": \"high\"}\n])\n```\n\n---\n\n# PHASE 1: CODEBASE ANALYSIS (PARALLEL EXPLORATION)\n\n**Mark phase-1 as in_progress.**\n\n## 1.1: Launch Parallel Explore Agents (BACKGROUND)\n\nFire ALL of these simultaneously using `task`:\n\n```\n// Agent 1: Find the refactoring target\ntask(\n subagent_type=\"trinity\",\n run_in_background=true,\n prompt=\"Find all occurrences and definitions of [TARGET]. \n Report: file paths, line numbers, usage patterns.\"\n)\n\n// Agent 2: Find related code\ntask(\n subagent_type=\"trinity\", \n run_in_background=true,\n prompt=\"Find all code that imports, uses, or depends on [TARGET].\n Report: dependency chains, import graphs.\"\n)\n\n// Agent 3: Find similar patterns\ntask(\n subagent_type=\"trinity\",\n run_in_background=true,\n prompt=\"Find similar code patterns to [TARGET] in the codebase.\n Report: analogous implementations, established conventions.\"\n)\n\n// Agent 4: Find tests\ntask(\n subagent_type=\"trinity\",\n run_in_background=true,\n prompt=\"Find all test files related to [TARGET].\n Report: test file paths, test case names, coverage indicators.\"\n)\n\n// Agent 5: Architecture context\ntask(\n subagent_type=\"trinity\",\n run_in_background=true,\n prompt=\"Find architectural patterns and module organization around [TARGET].\n Report: module boundaries, layer structure, design patterns in use.\"\n)\n```\n\n## 1.2: Direct Tool Exploration (WHILE AGENTS RUN)\n\nWhile background agents are running, use direct tools:\n\n### LSP Tools for Precise Analysis:\n\n```typescript\n// Find definition(s)\nLspGotoDefinition(filePath, line, character) // Where is it defined?\n\n// Find ALL usages across workspace\nLspFindReferences(filePath, line, character, includeDeclaration=true)\n\n// Get file structure\nLspDocumentSymbols(filePath) // Hierarchical outline\nLspWorkspaceSymbols(filePath, query=\"[target_symbol]\") // Search by name\n\n// Get current diagnostics\nlsp_diagnostics(filePath) // Errors, warnings before we start\n```\n\n### AST-Grep for Pattern Analysis:\n\n```typescript\n// Find structural patterns\nast_grep_search(\n pattern=\"function $NAME($$$) { $$$ }\", // or relevant pattern\n lang=\"typescript\", // or relevant language\n paths=[\"src/\"]\n)\n\n// Preview refactoring (DRY RUN)\nast_grep_replace(\n pattern=\"[old_pattern]\",\n rewrite=\"[new_pattern]\",\n lang=\"[language]\",\n dryRun=true // ALWAYS preview first\n)\n```\n\n### Grep for Text Patterns:\n\n```\ngrep(pattern=\"[search_term]\", path=\"src/\", include=\"*.ts\")\n```\n\n## 1.3: Collect Background Results\n\n```\nbackground_output(task_id=\"[agent_1_id]\")\nbackground_output(task_id=\"[agent_2_id]\")\n...\n```\n\n**Mark phase-1 as completed after all results collected.**\n\n---\n\n# PHASE 2: BUILD CODEMAP (DEPENDENCY MAPPING)\n\n**Mark phase-2 as in_progress.**\n\n## 2.1: Construct Definitive Codemap\n\nBased on Phase 1 results, build:\n\n```\n## CODEMAP: [TARGET]\n\n### Core Files (Direct Impact)\n- `path/to/file.ts:L10-L50` - Primary definition\n- `path/to/file2.ts:L25` - Key usage\n\n### Dependency Graph\n```\n[TARGET] \n\u251C\u2500\u2500 imports from: \n\u2502 \u251C\u2500\u2500 module-a (types)\n\u2502 \u2514\u2500\u2500 module-b (utils)\n\u251C\u2500\u2500 imported by:\n\u2502 \u251C\u2500\u2500 consumer-1.ts\n\u2502 \u251C\u2500\u2500 consumer-2.ts\n\u2502 \u2514\u2500\u2500 consumer-3.ts\n\u2514\u2500\u2500 used by:\n \u251C\u2500\u2500 handler.ts (direct call)\n \u2514\u2500\u2500 service.ts (dependency injection)\n```\n\n### Impact Zones\n| Zone | Risk Level | Files Affected | Test Coverage |\n|------|------------|----------------|---------------|\n| Core | HIGH | 3 files | 85% covered |\n| Consumers | MEDIUM | 8 files | 70% covered |\n| Edge | LOW | 2 files | 50% covered |\n\n### Established Patterns\n- Pattern A: [description] - used in N places\n- Pattern B: [description] - established convention\n```\n\n## 2.2: Identify Refactoring Constraints\n\nBased on codemap:\n- **MUST follow**: [existing patterns identified]\n- **MUST NOT break**: [critical dependencies]\n- **Safe to change**: [isolated code zones]\n- **Requires migration**: [breaking changes impact]\n\n**Mark phase-2 as completed.**\n\n---\n\n# PHASE 3: TEST ASSESSMENT (VERIFICATION STRATEGY)\n\n**Mark phase-3 as in_progress.**\n\n## 3.1: Detect Test Infrastructure\n\n```bash\n# Check for test commands\ncat package.json | jq '.scripts | keys[] | select(test(\"test\"))'\n\n# Or for Python\nls -la pytest.ini pyproject.toml setup.cfg\n\n# Or for Go\nls -la *_test.go\n```\n\n## 3.2: Analyze Test Coverage\n\n```\n// Find all tests related to target\ntask(\n subagent_type=\"trinity\",\n run_in_background=false, // Need this synchronously\n prompt=\"Analyze test coverage for [TARGET]:\n 1. Which test files cover this code?\n 2. What test cases exist?\n 3. Are there integration tests?\n 4. What edge cases are tested?\n 5. Estimated coverage percentage?\"\n)\n```\n\n## 3.3: Determine Verification Strategy\n\nBased on test analysis:\n\n| Coverage Level | Strategy |\n|----------------|----------|\n| HIGH (>80%) | Run existing tests after each step |\n| MEDIUM (50-80%) | Run tests + add safety assertions |\n| LOW (<50%) | **PAUSE**: Propose adding tests first |\n| NONE | **BLOCK**: Refuse aggressive refactoring |\n\n**If coverage is LOW or NONE, ask user:**\n\n```\nTest coverage for [TARGET] is [LEVEL].\n\n**Risk Assessment**: Refactoring without adequate tests is dangerous.\n\nOptions:\n1. Add tests first, then refactor (RECOMMENDED)\n2. Proceed with extra caution, manual verification required\n3. Abort refactoring\n\nWhich approach do you prefer?\n```\n\n## 3.4: Document Verification Plan\n\n```\n## VERIFICATION PLAN\n\n### Test Commands\n- Unit: `bun test` / `npm test` / `pytest` / etc.\n- Integration: [command if exists]\n- Type check: `tsc --noEmit` / `pyright` / etc.\n\n### Verification Checkpoints\nAfter each refactoring step:\n1. lsp_diagnostics \u2192 zero new errors\n2. Run test command \u2192 all pass\n3. Type check \u2192 clean\n\n### Regression Indicators\n- [Specific test that must pass]\n- [Behavior that must be preserved]\n- [API contract that must not change]\n```\n\n**Mark phase-3 as completed.**\n\n---\n\n# PHASE 4: PLAN GENERATION (PLAN AGENT)\n\n**Mark phase-4 as in_progress.**\n\n## 4.1: Invoke Plan Agent\n\n```\nTask(\n subagent_type=\"plan\",\n prompt=\"Create a detailed refactoring plan:\n\n ## Refactoring Goal\n [User's original request]\n\n ## Codemap (from Phase 2)\n [Insert codemap here]\n\n ## Test Coverage (from Phase 3)\n [Insert verification plan here]\n\n ## Constraints\n - MUST follow existing patterns: [list]\n - MUST NOT break: [critical paths]\n - MUST run tests after each step\n\n ## Requirements\n 1. Break down into atomic refactoring steps\n 2. Each step must be independently verifiable\n 3. Order steps by dependency (what must happen first)\n 4. Specify exact files and line ranges for each step\n 5. Include rollback strategy for each step\n 6. Define commit checkpoints\"\n)\n```\n\n## 4.2: Review and Validate Plan\n\nAfter receiving plan from Plan agent:\n\n1. **Verify completeness**: All identified files addressed?\n2. **Verify safety**: Each step reversible?\n3. **Verify order**: Dependencies respected?\n4. **Verify verification**: Test commands specified?\n\n## 4.3: Register Detailed Todos\n\nConvert Plan agent output into granular todos:\n\n```\nTodoWrite([\n // Each step from the plan becomes a todo\n {\"id\": \"refactor-1\", \"content\": \"Step 1: [description]\", \"status\": \"pending\", \"priority\": \"high\"},\n {\"id\": \"verify-1\", \"content\": \"Verify Step 1: run tests\", \"status\": \"pending\", \"priority\": \"high\"},\n {\"id\": \"refactor-2\", \"content\": \"Step 2: [description]\", \"status\": \"pending\", \"priority\": \"medium\"},\n {\"id\": \"verify-2\", \"content\": \"Verify Step 2: run tests\", \"status\": \"pending\", \"priority\": \"medium\"},\n // ... continue for all steps\n])\n```\n\n**Mark phase-4 as completed.**\n\n---\n\n# PHASE 5: EXECUTE REFACTORING (DETERMINISTIC EXECUTION)\n\n**Mark phase-5 as in_progress.**\n\n## 5.1: Execution Protocol\n\nFor EACH refactoring step:\n\n### Pre-Step\n1. Mark step todo as `in_progress`\n2. Read current file state\n3. Verify lsp_diagnostics is baseline\n\n### Execute Step\nUse appropriate tool:\n\n**For Symbol Renames:**\n```typescript\nlsp_prepare_rename(filePath, line, character) // Validate rename is possible\nlsp_rename(filePath, line, character, newName) // Execute rename\n```\n\n**For Pattern Transformations:**\n```typescript\n// Preview first\nast_grep_replace(pattern, rewrite, lang, dryRun=true)\n\n// If preview looks good, execute\nast_grep_replace(pattern, rewrite, lang, dryRun=false)\n```\n\n**For Structural Changes:**\n```typescript\n// Use Edit tool for precise changes\nedit(filePath, oldString, newString)\n```\n\n### Post-Step Verification (MANDATORY)\n\n```typescript\n// 1. Check diagnostics\nlsp_diagnostics(filePath) // Must be clean or same as baseline\n\n// 2. Run tests\nbash(\"bun test\") // Or appropriate test command\n\n// 3. Type check\nbash(\"tsc --noEmit\") // Or appropriate type check\n```\n\n### Step Completion\n1. If verification passes \u2192 Mark step todo as `completed`\n2. If verification fails \u2192 **STOP AND FIX**\n\n## 5.2: Failure Recovery Protocol\n\nIf ANY verification fails:\n\n1. **STOP** immediately\n2. **REVERT** the failed change\n3. **DIAGNOSE** what went wrong\n4. **OPTIONS**:\n - Fix the issue and retry\n - Skip this step (if optional)\n - Consult oracle agent for help\n - Ask user for guidance\n\n**NEVER proceed to next step with broken tests.**\n\n## 5.3: Commit Checkpoints\n\nAfter each logical group of changes:\n\n```bash\ngit add [changed-files]\ngit commit -m \"refactor(scope): description\n\n[details of what was changed and why]\"\n```\n\n**Mark phase-5 as completed when all refactoring steps done.**\n\n---\n\n# PHASE 6: FINAL VERIFICATION (REGRESSION CHECK)\n\n**Mark phase-6 as in_progress.**\n\n## 6.1: Full Test Suite\n\n```bash\n# Run complete test suite\nbun test # or npm test, pytest, go test, etc.\n```\n\n## 6.2: Type Check\n\n```bash\n# Full type check\ntsc --noEmit # or equivalent\n```\n\n## 6.3: Lint Check\n\n```bash\n# Run linter\neslint . # or equivalent\n```\n\n## 6.4: Build Verification (if applicable)\n\n```bash\n# Ensure build still works\nbun run build # or npm run build, etc.\n```\n\n## 6.5: Final Diagnostics\n\n```typescript\n// Check all changed files\nfor (file of changedFiles) {\n lsp_diagnostics(file) // Must all be clean\n}\n```\n\n## 6.6: Generate Summary\n\n```markdown\n## Refactoring Complete\n\n### What Changed\n- [List of changes made]\n\n### Files Modified\n- `path/to/file.ts` - [what changed]\n- `path/to/file2.ts` - [what changed]\n\n### Verification Results\n- Tests: PASSED (X/Y passing)\n- Type Check: CLEAN\n- Lint: CLEAN\n- Build: SUCCESS\n\n### No Regressions Detected\nAll existing tests pass. No new errors introduced.\n```\n\n**Mark phase-6 as completed.**\n\n---\n\n# CRITICAL RULES\n\n## NEVER DO\n- Skip lsp_diagnostics check after changes\n- Proceed with failing tests\n- Make changes without understanding impact\n- Use `as any`, `@ts-ignore`, `@ts-expect-error`\n- Delete tests to make them pass\n- Commit broken code\n- Refactor without understanding existing patterns\n\n## ALWAYS DO\n- Understand before changing\n- Preview before applying (ast_grep dryRun=true)\n- Verify after every change\n- Follow existing codebase patterns\n- Keep todos updated in real-time\n- Commit at logical checkpoints\n- Report issues immediately\n\n## ABORT CONDITIONS\nIf any of these occur, **STOP and consult user**:\n- Test coverage is zero for target code\n- Changes would break public API\n- Refactoring scope is unclear\n- 3 consecutive verification failures\n- User-defined constraints violated\n\n---\n\n# Tool Usage Philosophy\n\nYou already know these tools. Use them intelligently:\n\n## LSP Tools\nLeverage LSP tools for precision analysis. Key patterns:\n- **Understand before changing**: `LspGotoDefinition` to grasp context\n- **Impact analysis**: `LspFindReferences` to map all usages before modification\n- **Safe refactoring**: `lsp_prepare_rename` \u2192 `lsp_rename` for symbol renames\n- **Continuous verification**: `lsp_diagnostics` after every change\n\n## AST-Grep\nUse `ast_grep_search` and `ast_grep_replace` for structural transformations.\n**Critical**: Always `dryRun=true` first, review, then execute.\n\n## Agents\n- `explore`: Parallel codebase pattern discovery\n- `plan`: Detailed refactoring plan generation\n- `oracle`: Read-only consultation for complex architectural decisions and debugging\n- `librarian`: **Use proactively** when encountering deprecated methods or library migration tasks. Query official docs and OSS examples for modern replacements.\n\n## Deprecated Code & Library Migration\nWhen you encounter deprecated methods/APIs during refactoring:\n1. Fire `librarian` to find the recommended modern alternative\n2. **DO NOT auto-upgrade to latest version** unless user explicitly requests migration\n3. If user requests library migration, use `librarian` to fetch latest API docs before making changes\n\n---\n\n**Remember: Refactoring without tests is reckless. Refactoring without understanding is destructive. This command ensures you do neither.**\n\n<user-request>\n$ARGUMENTS\n</user-request>\n";
|
|
@@ -1,4 +1,6 @@
|
|
|
1
1
|
import type { PendingContext, RegisterContextOptions } from "./types";
|
|
2
|
+
export declare const MAX_MERGED_CHARS = 6000;
|
|
3
|
+
export declare const MAX_PER_SOURCE_CHARS = 2000;
|
|
2
4
|
export declare class ContextCollector {
|
|
3
5
|
private sessions;
|
|
4
6
|
register(sessionID: string, options: RegisterContextOptions): void;
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
export { ContextCollector, contextCollector } from "./collector";
|
|
1
|
+
export { ContextCollector, contextCollector, MAX_MERGED_CHARS, MAX_PER_SOURCE_CHARS } from "./collector";
|
|
2
2
|
export { createContextInjectorMessagesTransformHook, } from "./injector";
|
|
3
3
|
export type { ContextEntry, ContextPriority, ContextSourceType, InjectionStrategy, MessageContext, OutputParts, PendingContext, RegisterContextOptions, } from "./types";
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
export declare const AGENT_USAGE_REMINDER_STORAGE: string;
|
|
2
2
|
export declare const TARGET_TOOLS: Set<string>;
|
|
3
3
|
export declare const AGENT_TOOLS: Set<string>;
|
|
4
|
+
export declare const MAX_AGENT_USAGE_REMINDERS = 3;
|
|
4
5
|
export declare const REMINDER_MESSAGE = "\n[Agent Usage Reminder]\n\nYou called a search/fetch tool directly without leveraging specialized agents.\n\nRECOMMENDED: Use task with explore/librarian agents for better results:\n\n```\n// Parallel exploration - fire multiple agents simultaneously\ntask(agent=\"trinity\", prompt=\"Find all files matching pattern X\")\ntask(agent=\"trinity\", prompt=\"Search for implementation of Y\") \ntask(agent=\"operator\", prompt=\"Lookup documentation for Z\")\n\n// Then continue your work while they run in background\n// System will notify you when each completes\n```\n\nWHY:\n- Agents can perform deeper, more thorough searches\n- Background tasks run in parallel, saving time\n- Specialized agents have domain expertise\n- Reduces context window usage in main session\n\nALWAYS prefer: Multiple parallel task calls > Direct tool calls\n";
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
export declare const HOOK_NAME = "context-mode-enforcer";
|
|
2
2
|
export declare const WARN_MESSAGE_READ = "Use ctx_search / ctx_batch_execute / ctx_execute for analysis \u2014 raw read/grep/glob bypasses FTS5 sandbox and pollutes context. Use Read only with hashline IDs for Edit (non-plan paths; .matrixx/plans/*.md must use plan_read/plan_update).";
|
|
3
|
-
export declare const BLOCK_MESSAGE_GREP_GLOB
|
|
3
|
+
export declare const BLOCK_MESSAGE_GREP_GLOB: string;
|
|
4
4
|
export declare const WARN_MESSAGE_BASH_READ = "Use ctx_* / Read tool instead of `cat`/`head`/`tail`/`grep` via bash for analysis. Raw bash file reads bypass sandbox.";
|
|
5
5
|
export declare const DEFAULT_BLOCKED_TOOLS: readonly ["grep", "glob"];
|
|
6
6
|
export declare const WARN_ONLY_TOOLS: readonly ["read"];
|
|
@@ -1,5 +1,9 @@
|
|
|
1
1
|
export declare const HOOK_NAME = "task-continuation-enforcer";
|
|
2
2
|
export declare const DEFAULT_SKIP_AGENTS: string[];
|
|
3
|
+
export declare const EXPLORER_AGENTS: string[];
|
|
4
|
+
export declare function hasNonExplorerBgTasks(tasks: Array<{
|
|
5
|
+
agent?: string;
|
|
6
|
+
}>): boolean;
|
|
3
7
|
export declare const CONTINUATION_PROMPT: string;
|
|
4
8
|
export declare const BOOTSTRAP_PROMPT: string;
|
|
5
9
|
export declare const COUNTDOWN_SECONDS = 2;
|