opencode-matrixx 2.6.13 → 2.6.14
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/README.md +25 -21
- package/dist/agents/architect/default.d.ts +1 -1
- package/dist/agents/architect/gpt.d.ts +1 -1
- package/dist/agents/builtin-agents/architect-agent.d.ts +0 -1
- package/dist/agents/builtin-agents/general-agents.d.ts +0 -1
- package/dist/agents/builtin-agents/keymaker-agent.d.ts +0 -1
- package/dist/agents/builtin-agents/morpheus-agent.d.ts +0 -1
- package/dist/agents/builtin-agents.d.ts +1 -1
- package/dist/agents/keymaker.d.ts +1 -1
- package/dist/agents/morpheus.d.ts +1 -1
- package/dist/agents/mouse/agent.d.ts +2 -2
- package/dist/agents/mouse/deepseek.d.ts +1 -1
- package/dist/agents/mouse/default.d.ts +1 -1
- package/dist/agents/mouse/gpt.d.ts +1 -1
- package/dist/agents/mouse/mimo.d.ts +1 -1
- package/dist/agents/mouse/qwen.d.ts +1 -1
- package/dist/agents/mouse/shared.d.ts +3 -3
- package/dist/agents/oracle/plan-generation.d.ts +1 -1
- package/dist/agents/seraph.d.ts +1 -1
- package/dist/cli.js +11 -9
- package/dist/config/schema/experimental.d.ts +1 -1
- package/dist/config/schema/hooks.d.ts +2 -5
- package/dist/config/schema/matrixx-config.d.ts +4 -6
- package/dist/config/schema/tasks.d.ts +5 -1
- package/dist/create-hooks.d.ts +1 -4
- package/dist/features/background-agent/manager.d.ts +5 -2
- package/dist/features/background-agent/reconcile.d.ts +8 -1
- package/dist/features/builtin-commands/templates/handoff.d.ts +1 -1
- package/dist/features/builtin-commands/templates/init-deep.d.ts +1 -1
- package/dist/features/builtin-commands/templates/refactor.d.ts +1 -1
- package/dist/features/builtin-commands/templates/remove-deadcode.d.ts +1 -1
- package/dist/features/builtin-commands/templates/stop-continuation.d.ts +1 -1
- package/dist/features/task-session-scope/ancestry.d.ts +23 -0
- package/dist/features/task-session-scope/index.d.ts +2 -0
- package/dist/features/task-session-scope/session-task-pending.d.ts +83 -0
- package/dist/hooks/architect/system-reminder-templates.d.ts +1 -1
- package/dist/hooks/index.d.ts +1 -5
- package/dist/hooks/keyword-detector/ultrawork/deepseek.d.ts +1 -1
- package/dist/hooks/keyword-detector/ultrawork/default.d.ts +1 -1
- package/dist/hooks/keyword-detector/ultrawork/gemini.d.ts +1 -1
- package/dist/hooks/keyword-detector/ultrawork/glm.d.ts +1 -1
- package/dist/hooks/keyword-detector/ultrawork/mimo.d.ts +1 -1
- package/dist/hooks/plan-persister/hook.d.ts +1 -1
- package/dist/hooks/session-notification-scheduler.d.ts +1 -1
- package/dist/hooks/session-notification.d.ts +9 -2
- package/dist/hooks/task-continuation-enforcer/handler.d.ts +0 -1
- package/dist/hooks/task-continuation-enforcer/index.d.ts +0 -1
- package/dist/hooks/task-continuation-enforcer/staleness.d.ts +10 -0
- package/dist/hooks/task-continuation-enforcer/todo.d.ts +2 -1
- package/dist/hooks/task-continuation-enforcer/types.d.ts +0 -8
- package/dist/hooks/task-notepad-writer/constants.d.ts +42 -0
- package/dist/hooks/task-notepad-writer/hook.d.ts +14 -0
- package/dist/hooks/task-notepad-writer/index.d.ts +2 -0
- package/dist/hooks/task-notepad-writer/notepad-path.d.ts +36 -0
- package/dist/index.js +1545 -2092
- package/dist/matrixx.schema.json +31 -18
- package/dist/plugin/hooks/create-continuation-hooks.d.ts +1 -3
- package/dist/plugin/hooks/create-core-hooks.d.ts +1 -2
- package/dist/plugin/hooks/create-tool-guard-hooks.d.ts +2 -3
- package/dist/plugin-handlers/task-permissions.d.ts +48 -0
- package/dist/shared/logger.d.ts +1 -0
- package/dist/shared/system-directive.d.ts +0 -1
- package/dist/shared/task-system-gating.d.ts +24 -4
- package/dist/tools/session-manager/constants.d.ts +1 -1
- package/dist/tools/session-manager/storage.d.ts +44 -0
- package/dist/tools/session-manager/tools.d.ts +2 -1
- package/dist/tools/task/create-one.d.ts +21 -0
- package/dist/tools/task/types.d.ts +56 -1
- package/package.json +1 -1
- package/dist/hooks/compaction-todo-preserver/hook.d.ts +0 -24
- package/dist/hooks/compaction-todo-preserver/index.d.ts +0 -2
- package/dist/hooks/session-todo-status.d.ts +0 -2
- package/dist/hooks/task-notepad/constants.d.ts +0 -10
- package/dist/hooks/task-notepad/hook.d.ts +0 -12
- package/dist/hooks/task-notepad/index.d.ts +0 -3
- package/dist/hooks/task-notepad/types.d.ts +0 -16
- package/dist/hooks/tasks-todowrite-disabler/constants.d.ts +0 -3
- package/dist/hooks/tasks-todowrite-disabler/hook.d.ts +0 -14
- package/dist/hooks/tasks-todowrite-disabler/index.d.ts +0 -2
- package/dist/hooks/todo-continuation-enforcer/abort-detection.d.ts +0 -4
- package/dist/hooks/todo-continuation-enforcer/constants.d.ts +0 -10
- package/dist/hooks/todo-continuation-enforcer/continuation-injection.d.ts +0 -12
- package/dist/hooks/todo-continuation-enforcer/countdown.d.ts +0 -14
- package/dist/hooks/todo-continuation-enforcer/handler.d.ts +0 -15
- package/dist/hooks/todo-continuation-enforcer/idle-event.d.ts +0 -11
- package/dist/hooks/todo-continuation-enforcer/index.d.ts +0 -4
- package/dist/hooks/todo-continuation-enforcer/message-directory.d.ts +0 -1
- package/dist/hooks/todo-continuation-enforcer/non-idle-events.d.ts +0 -6
- package/dist/hooks/todo-continuation-enforcer/session-state.d.ts +0 -10
- package/dist/hooks/todo-continuation-enforcer/todo.d.ts +0 -2
- package/dist/hooks/todo-continuation-enforcer/types.d.ts +0 -61
package/dist/cli.js
CHANGED
|
@@ -16098,7 +16098,7 @@ var ExperimentalConfigSchema = exports_external.object({
|
|
|
16098
16098
|
auto_resume: exports_external.boolean().optional(),
|
|
16099
16099
|
preemptive_compaction: exports_external.boolean().optional(),
|
|
16100
16100
|
truncate_all_tool_outputs: exports_external.boolean().optional(),
|
|
16101
|
-
task_system: exports_external.boolean().optional()
|
|
16101
|
+
task_system: exports_external.boolean().optional(),
|
|
16102
16102
|
plugin_load_timeout_ms: exports_external.number().min(1000).optional(),
|
|
16103
16103
|
context_warning_threshold: exports_external.number().min(0.1).max(0.95).optional(),
|
|
16104
16104
|
preemptive_compaction_threshold: exports_external.number().min(0.1).max(0.95).optional(),
|
|
@@ -16117,7 +16117,6 @@ var HeadroomConfigSchema = exports_external.object({
|
|
|
16117
16117
|
// src/config/schema/hooks.ts
|
|
16118
16118
|
var HookNameEnum = exports_external.enum([
|
|
16119
16119
|
"task-continuation-enforcer",
|
|
16120
|
-
"todo-continuation-enforcer",
|
|
16121
16120
|
"context-window-monitor",
|
|
16122
16121
|
"session-recovery",
|
|
16123
16122
|
"session-notification",
|
|
@@ -16141,7 +16140,6 @@ var HookNameEnum = exports_external.enum([
|
|
|
16141
16140
|
"matrix-loop",
|
|
16142
16141
|
"category-skill-reminder",
|
|
16143
16142
|
"compaction-context-injector",
|
|
16144
|
-
"compaction-todo-preserver",
|
|
16145
16143
|
"auto-slash-command",
|
|
16146
16144
|
"edit-error-recovery",
|
|
16147
16145
|
"delegate-task-retry",
|
|
@@ -16153,7 +16151,6 @@ var HookNameEnum = exports_external.enum([
|
|
|
16153
16151
|
"unstable-agent-babysitter",
|
|
16154
16152
|
"task-resume-info",
|
|
16155
16153
|
"stop-continuation-guard",
|
|
16156
|
-
"tasks-todowrite-disabler",
|
|
16157
16154
|
"write-existing-file-guard",
|
|
16158
16155
|
"anthropic-effort",
|
|
16159
16156
|
"hashline-read-enhancer",
|
|
@@ -16168,7 +16165,6 @@ var HookNameEnum = exports_external.enum([
|
|
|
16168
16165
|
"webfetch-redirect-guard",
|
|
16169
16166
|
"tool-pair-validator",
|
|
16170
16167
|
"quality-gate",
|
|
16171
|
-
"task-notepad",
|
|
16172
16168
|
"design-intent-preserver",
|
|
16173
16169
|
"rtk-bash-rewriter",
|
|
16174
16170
|
"evolution-watcher",
|
|
@@ -16181,11 +16177,16 @@ var HookNameEnum = exports_external.enum([
|
|
|
16181
16177
|
"knowledge-hub-injector",
|
|
16182
16178
|
"knowledge-hub-search-nudge",
|
|
16183
16179
|
"dcp-nudge-sanitizer",
|
|
16184
|
-
"nudge-loop-breaker"
|
|
16180
|
+
"nudge-loop-breaker",
|
|
16181
|
+
"task-notepad-writer"
|
|
16185
16182
|
]);
|
|
16186
16183
|
var HookNameSchema = exports_external.union([
|
|
16187
16184
|
HookNameEnum,
|
|
16188
|
-
exports_external.literal("anthropic-context-window-limit-recovery").transform(() => "context-window-limit-recovery")
|
|
16185
|
+
exports_external.literal("anthropic-context-window-limit-recovery").transform(() => "context-window-limit-recovery"),
|
|
16186
|
+
exports_external.literal("todo-continuation-enforcer"),
|
|
16187
|
+
exports_external.literal("compaction-todo-preserver"),
|
|
16188
|
+
exports_external.literal("tasks-todowrite-disabler"),
|
|
16189
|
+
exports_external.literal("task-notepad")
|
|
16189
16190
|
]);
|
|
16190
16191
|
|
|
16191
16192
|
// src/config/schema/knowledge.ts
|
|
@@ -16278,7 +16279,7 @@ var MorpheusTasksConfigSchema = exports_external.object({
|
|
|
16278
16279
|
storage_path: exports_external.string().optional(),
|
|
16279
16280
|
task_list_id: exports_external.string().optional(),
|
|
16280
16281
|
scope: exports_external.enum(["global", "project"]).default("project").optional().describe("Task storage scope: project \u2192 .matrixx/tasks per project (default), global \u2192 ~/.config/opencode/tasks/{listId}"),
|
|
16281
|
-
stale_after_hours: exports_external.number().
|
|
16282
|
+
stale_after_hours: exports_external.number().min(0.25).optional().describe("Pending tasks with no file activity for this many hours are considered stale and excluded from task-continuation directives. Accepts fractional hours (minimum 0.25 = 15 minutes); there is no separate minutes companion key. Default 24."),
|
|
16282
16283
|
session_scoped: exports_external.boolean().default(true).optional().describe("When true, the task-continuation-enforcer only considers tasks created by the current session (or its subagent sessions). When false, all project tasks are considered regardless of session origin.")
|
|
16283
16284
|
});
|
|
16284
16285
|
var MorpheusConfigSchema = exports_external.object({
|
|
@@ -16410,7 +16411,8 @@ var TasksConfigSchema = exports_external.object({
|
|
|
16410
16411
|
scope: exports_external.enum(["global", "project"]).default("project").optional().describe("Task storage scope: project \u2192 .matrixx/tasks per project (default), global \u2192 <opencode-config>/tasks/{listId}"),
|
|
16411
16412
|
storage_path: exports_external.string().optional(),
|
|
16412
16413
|
task_list_id: exports_external.string().optional(),
|
|
16413
|
-
stale_after_hours: exports_external.number().
|
|
16414
|
+
stale_after_hours: exports_external.number().min(0.25).optional().describe("Pending tasks with no file activity for this many hours are considered stale and excluded from task-continuation directives. Accepts fractional hours (minimum 0.25 = 15 minutes); there is no separate minutes companion key. Default 24."),
|
|
16415
|
+
background_stale_after_hours: exports_external.number().min(0.25).default(2).optional().describe("Window used only by the background-agent completion gates: a pending/in_progress task with no file activity for this many hours stops blocking completion of its background handle. Separate from stale_after_hours because a missed nudge and a wedged handle are different failures. Accepts fractional hours (min 0.25). Default 2."),
|
|
16414
16416
|
session_scoped: exports_external.boolean().default(true).optional().describe("When true, the task-continuation-enforcer only considers tasks created by the current session (or its subagent sessions). When false, all project tasks are considered regardless of session origin."),
|
|
16415
16417
|
pollTimeoutMs: exports_external.number().min(60000).optional()
|
|
16416
16418
|
});
|
|
@@ -4,7 +4,7 @@ export declare const ExperimentalConfigSchema: z.ZodObject<{
|
|
|
4
4
|
auto_resume: z.ZodOptional<z.ZodBoolean>;
|
|
5
5
|
preemptive_compaction: z.ZodOptional<z.ZodBoolean>;
|
|
6
6
|
truncate_all_tool_outputs: z.ZodOptional<z.ZodBoolean>;
|
|
7
|
-
task_system: z.
|
|
7
|
+
task_system: z.ZodOptional<z.ZodBoolean>;
|
|
8
8
|
plugin_load_timeout_ms: z.ZodOptional<z.ZodNumber>;
|
|
9
9
|
context_warning_threshold: z.ZodOptional<z.ZodNumber>;
|
|
10
10
|
preemptive_compaction_threshold: z.ZodOptional<z.ZodNumber>;
|
|
@@ -7,7 +7,6 @@ export declare const HookNameSchema: z.ZodUnion<readonly [z.ZodEnum<{
|
|
|
7
7
|
"evolution-watcher": "evolution-watcher";
|
|
8
8
|
"evolution-compressor": "evolution-compressor";
|
|
9
9
|
"task-continuation-enforcer": "task-continuation-enforcer";
|
|
10
|
-
"todo-continuation-enforcer": "todo-continuation-enforcer";
|
|
11
10
|
"context-window-monitor": "context-window-monitor";
|
|
12
11
|
"session-recovery": "session-recovery";
|
|
13
12
|
"session-notification": "session-notification";
|
|
@@ -30,7 +29,6 @@ export declare const HookNameSchema: z.ZodUnion<readonly [z.ZodEnum<{
|
|
|
30
29
|
"thinking-block-validator": "thinking-block-validator";
|
|
31
30
|
"category-skill-reminder": "category-skill-reminder";
|
|
32
31
|
"compaction-context-injector": "compaction-context-injector";
|
|
33
|
-
"compaction-todo-preserver": "compaction-todo-preserver";
|
|
34
32
|
"auto-slash-command": "auto-slash-command";
|
|
35
33
|
"edit-error-recovery": "edit-error-recovery";
|
|
36
34
|
"delegate-task-retry": "delegate-task-retry";
|
|
@@ -40,7 +38,6 @@ export declare const HookNameSchema: z.ZodUnion<readonly [z.ZodEnum<{
|
|
|
40
38
|
"unstable-agent-babysitter": "unstable-agent-babysitter";
|
|
41
39
|
"task-resume-info": "task-resume-info";
|
|
42
40
|
"stop-continuation-guard": "stop-continuation-guard";
|
|
43
|
-
"tasks-todowrite-disabler": "tasks-todowrite-disabler";
|
|
44
41
|
"write-existing-file-guard": "write-existing-file-guard";
|
|
45
42
|
"anthropic-effort": "anthropic-effort";
|
|
46
43
|
"hashline-read-enhancer": "hashline-read-enhancer";
|
|
@@ -54,7 +51,6 @@ export declare const HookNameSchema: z.ZodUnion<readonly [z.ZodEnum<{
|
|
|
54
51
|
"read-image-resizer": "read-image-resizer";
|
|
55
52
|
"webfetch-redirect-guard": "webfetch-redirect-guard";
|
|
56
53
|
"tool-pair-validator": "tool-pair-validator";
|
|
57
|
-
"task-notepad": "task-notepad";
|
|
58
54
|
"design-intent-preserver": "design-intent-preserver";
|
|
59
55
|
"rtk-bash-rewriter": "rtk-bash-rewriter";
|
|
60
56
|
"evolution-hitl": "evolution-hitl";
|
|
@@ -66,5 +62,6 @@ export declare const HookNameSchema: z.ZodUnion<readonly [z.ZodEnum<{
|
|
|
66
62
|
"knowledge-hub-search-nudge": "knowledge-hub-search-nudge";
|
|
67
63
|
"dcp-nudge-sanitizer": "dcp-nudge-sanitizer";
|
|
68
64
|
"nudge-loop-breaker": "nudge-loop-breaker";
|
|
69
|
-
|
|
65
|
+
"task-notepad-writer": "task-notepad-writer";
|
|
66
|
+
}>, z.ZodPipe<z.ZodLiteral<"anthropic-context-window-limit-recovery">, z.ZodTransform<"context-window-limit-recovery", "anthropic-context-window-limit-recovery">>, z.ZodLiteral<"todo-continuation-enforcer">, z.ZodLiteral<"compaction-todo-preserver">, z.ZodLiteral<"tasks-todowrite-disabler">, z.ZodLiteral<"task-notepad">]>;
|
|
70
67
|
export type HookName = z.infer<typeof HookNameSchema>;
|
|
@@ -80,7 +80,6 @@ export declare const MatrixxConfigSchema: z.ZodObject<{
|
|
|
80
80
|
"evolution-watcher": "evolution-watcher";
|
|
81
81
|
"evolution-compressor": "evolution-compressor";
|
|
82
82
|
"task-continuation-enforcer": "task-continuation-enforcer";
|
|
83
|
-
"todo-continuation-enforcer": "todo-continuation-enforcer";
|
|
84
83
|
"context-window-monitor": "context-window-monitor";
|
|
85
84
|
"session-recovery": "session-recovery";
|
|
86
85
|
"session-notification": "session-notification";
|
|
@@ -103,7 +102,6 @@ export declare const MatrixxConfigSchema: z.ZodObject<{
|
|
|
103
102
|
"thinking-block-validator": "thinking-block-validator";
|
|
104
103
|
"category-skill-reminder": "category-skill-reminder";
|
|
105
104
|
"compaction-context-injector": "compaction-context-injector";
|
|
106
|
-
"compaction-todo-preserver": "compaction-todo-preserver";
|
|
107
105
|
"auto-slash-command": "auto-slash-command";
|
|
108
106
|
"edit-error-recovery": "edit-error-recovery";
|
|
109
107
|
"delegate-task-retry": "delegate-task-retry";
|
|
@@ -113,7 +111,6 @@ export declare const MatrixxConfigSchema: z.ZodObject<{
|
|
|
113
111
|
"unstable-agent-babysitter": "unstable-agent-babysitter";
|
|
114
112
|
"task-resume-info": "task-resume-info";
|
|
115
113
|
"stop-continuation-guard": "stop-continuation-guard";
|
|
116
|
-
"tasks-todowrite-disabler": "tasks-todowrite-disabler";
|
|
117
114
|
"write-existing-file-guard": "write-existing-file-guard";
|
|
118
115
|
"anthropic-effort": "anthropic-effort";
|
|
119
116
|
"hashline-read-enhancer": "hashline-read-enhancer";
|
|
@@ -127,7 +124,6 @@ export declare const MatrixxConfigSchema: z.ZodObject<{
|
|
|
127
124
|
"read-image-resizer": "read-image-resizer";
|
|
128
125
|
"webfetch-redirect-guard": "webfetch-redirect-guard";
|
|
129
126
|
"tool-pair-validator": "tool-pair-validator";
|
|
130
|
-
"task-notepad": "task-notepad";
|
|
131
127
|
"design-intent-preserver": "design-intent-preserver";
|
|
132
128
|
"rtk-bash-rewriter": "rtk-bash-rewriter";
|
|
133
129
|
"evolution-hitl": "evolution-hitl";
|
|
@@ -139,7 +135,8 @@ export declare const MatrixxConfigSchema: z.ZodObject<{
|
|
|
139
135
|
"knowledge-hub-search-nudge": "knowledge-hub-search-nudge";
|
|
140
136
|
"dcp-nudge-sanitizer": "dcp-nudge-sanitizer";
|
|
141
137
|
"nudge-loop-breaker": "nudge-loop-breaker";
|
|
142
|
-
|
|
138
|
+
"task-notepad-writer": "task-notepad-writer";
|
|
139
|
+
}>, z.ZodPipe<z.ZodLiteral<"anthropic-context-window-limit-recovery">, z.ZodTransform<"context-window-limit-recovery", "anthropic-context-window-limit-recovery">>, z.ZodLiteral<"todo-continuation-enforcer">, z.ZodLiteral<"compaction-todo-preserver">, z.ZodLiteral<"tasks-todowrite-disabler">, z.ZodLiteral<"task-notepad">]>>>;
|
|
143
140
|
disabled_commands: z.ZodOptional<z.ZodArray<z.ZodEnum<{
|
|
144
141
|
"init-deep": "init-deep";
|
|
145
142
|
"matrix-loop": "matrix-loop";
|
|
@@ -1565,7 +1562,7 @@ export declare const MatrixxConfigSchema: z.ZodObject<{
|
|
|
1565
1562
|
auto_resume: z.ZodOptional<z.ZodBoolean>;
|
|
1566
1563
|
preemptive_compaction: z.ZodOptional<z.ZodBoolean>;
|
|
1567
1564
|
truncate_all_tool_outputs: z.ZodOptional<z.ZodBoolean>;
|
|
1568
|
-
task_system: z.
|
|
1565
|
+
task_system: z.ZodOptional<z.ZodBoolean>;
|
|
1569
1566
|
plugin_load_timeout_ms: z.ZodOptional<z.ZodNumber>;
|
|
1570
1567
|
context_warning_threshold: z.ZodOptional<z.ZodNumber>;
|
|
1571
1568
|
preemptive_compaction_threshold: z.ZodOptional<z.ZodNumber>;
|
|
@@ -1761,6 +1758,7 @@ export declare const MatrixxConfigSchema: z.ZodObject<{
|
|
|
1761
1758
|
storage_path: z.ZodOptional<z.ZodString>;
|
|
1762
1759
|
task_list_id: z.ZodOptional<z.ZodString>;
|
|
1763
1760
|
stale_after_hours: z.ZodOptional<z.ZodNumber>;
|
|
1761
|
+
background_stale_after_hours: z.ZodOptional<z.ZodDefault<z.ZodNumber>>;
|
|
1764
1762
|
session_scoped: z.ZodOptional<z.ZodDefault<z.ZodBoolean>>;
|
|
1765
1763
|
pollTimeoutMs: z.ZodOptional<z.ZodNumber>;
|
|
1766
1764
|
}, z.core.$strip>>;
|
|
@@ -5,9 +5,12 @@ import { z } from "zod";
|
|
|
5
5
|
*
|
|
6
6
|
* Legacy locations still parse (backward compat) and act as fallback
|
|
7
7
|
* with LOWER precedence — explicit `tasks.*` always wins:
|
|
8
|
-
* - `experimental.task_system` / `new_task_system_enabled` → `tasks.enabled`
|
|
9
8
|
* - `morpheus.tasks.*` → `tasks.*` (same key names)
|
|
10
9
|
* - `task.pollTimeoutMs` → `tasks.pollTimeoutMs`
|
|
10
|
+
*
|
|
11
|
+
* `experimental.task_system` and `new_task_system_enabled` are NOT listed as
|
|
12
|
+
* fallbacks any more: both are deprecated no-ops since v2.7 (the legacy todo
|
|
13
|
+
* system they toggled is removed) and are ignored.
|
|
11
14
|
* See `resolveTasksConfig()` in `src/shared/task-system-gating.ts`.
|
|
12
15
|
*/
|
|
13
16
|
export declare const TasksConfigSchema: z.ZodObject<{
|
|
@@ -19,6 +22,7 @@ export declare const TasksConfigSchema: z.ZodObject<{
|
|
|
19
22
|
storage_path: z.ZodOptional<z.ZodString>;
|
|
20
23
|
task_list_id: z.ZodOptional<z.ZodString>;
|
|
21
24
|
stale_after_hours: z.ZodOptional<z.ZodNumber>;
|
|
25
|
+
background_stale_after_hours: z.ZodOptional<z.ZodDefault<z.ZodNumber>>;
|
|
22
26
|
session_scoped: z.ZodOptional<z.ZodDefault<z.ZodBoolean>>;
|
|
23
27
|
pollTimeoutMs: z.ZodOptional<z.ZodNumber>;
|
|
24
28
|
}, z.core.$strip>;
|
package/dist/create-hooks.d.ts
CHANGED
|
@@ -17,8 +17,6 @@ export declare function createHooks(args: {
|
|
|
17
17
|
autoSlashCommand: ReturnType<typeof import("./hooks").createAutoSlashCommandHook> | null;
|
|
18
18
|
stopContinuationGuard: ReturnType<typeof import("./hooks").createStopContinuationGuardHook> | null;
|
|
19
19
|
compactionContextInjector: ReturnType<typeof import("./hooks").createCompactionContextInjector> | null;
|
|
20
|
-
compactionTodoPreserver: ReturnType<typeof import("./hooks").createCompactionTodoPreserverHook> | null;
|
|
21
|
-
todoContinuationEnforcer: ReturnType<typeof import("./hooks").createTodoContinuationEnforcer> | null;
|
|
22
20
|
taskContinuationEnforcer: ReturnType<typeof import("./hooks").createTaskContinuationEnforcer> | null;
|
|
23
21
|
unstableAgentBabysitter: ReturnType<typeof import("./plugin/unstable-agent-babysitter").createUnstableAgentBabysitter> | null;
|
|
24
22
|
nudgeLoopBreaker: ReturnType<typeof import("./hooks").createNudgeLoopBreakerHook> | null;
|
|
@@ -42,7 +40,6 @@ export declare function createHooks(args: {
|
|
|
42
40
|
directoryAgentsInjector: ReturnType<typeof import("./hooks").createDirectoryAgentsInjectorHook> | null;
|
|
43
41
|
emptyTaskResponseDetector: ReturnType<typeof import("./hooks").createEmptyTaskResponseDetectorHook> | null;
|
|
44
42
|
rulesInjector: ReturnType<typeof import("./hooks").createRulesInjectorHook> | null;
|
|
45
|
-
tasksTodowriteDisabler: ReturnType<typeof import("./hooks").createTasksTodowriteDisablerHook> | null;
|
|
46
43
|
writeExistingFileGuard: ReturnType<typeof import("./hooks").createWriteExistingFileGuardHook> | null;
|
|
47
44
|
hashlineReadEnhancer: ReturnType<typeof import("./hooks").createHashlineReadEnhancerHook> | null;
|
|
48
45
|
secretLeakGuard: ReturnType<typeof import("./hooks").createSecretLeakGuardHook> | null;
|
|
@@ -53,8 +50,8 @@ export declare function createHooks(args: {
|
|
|
53
50
|
readImageResizer: ReturnType<typeof import("./hooks").createReadImageResizerHook> | null;
|
|
54
51
|
webfetchRedirectGuard: ReturnType<typeof import("./hooks").createWebFetchRedirectGuardHook> | null;
|
|
55
52
|
qualityGate: ReturnType<typeof import("./hooks").createQualityGateHook> | null;
|
|
56
|
-
taskNotepad: ReturnType<typeof import("./hooks").createTaskNotepadHook> | null;
|
|
57
53
|
taskEditGuard: ReturnType<typeof import("./hooks").createTaskEditGuardHook> | null;
|
|
54
|
+
taskNotepadWriter: ReturnType<typeof import("./hooks").createTaskNotepadWriterHook> | null;
|
|
58
55
|
documentReaderGuard: ReturnType<typeof import("./hooks").createDocumentReaderGuardHook> | null;
|
|
59
56
|
knowledgeHubGuard: ReturnType<typeof import("./hooks").createKnowledgeHubGuardHook> | null;
|
|
60
57
|
knowledgeHubSearchNudge: ReturnType<typeof import("./hooks").createKnowledgeHubSearchNudgeHook> | null;
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import type { PluginInput } from "@opencode-ai/plugin";
|
|
2
|
-
import type { BackgroundTaskConfig, DcpHandoffCompression, TmuxConfig } from "../../config/schema";
|
|
2
|
+
import type { BackgroundTaskConfig, DcpHandoffCompression, MatrixxConfig, TmuxConfig } from "../../config/schema";
|
|
3
3
|
import { TaskHistory } from "./task-history";
|
|
4
4
|
import type { BackgroundTask, LaunchInput, ResumeInput, ReviveInput } from "./types";
|
|
5
5
|
export interface EventProperties {
|
|
@@ -34,6 +34,8 @@ export declare class BackgroundManager {
|
|
|
34
34
|
private concurrencyManager;
|
|
35
35
|
private shutdownTriggered;
|
|
36
36
|
private config?;
|
|
37
|
+
/** Full plugin config — the only source of the `tasks.*` store location. */
|
|
38
|
+
private pluginConfig?;
|
|
37
39
|
private tmuxEnabled;
|
|
38
40
|
private onSubagentSessionCreated?;
|
|
39
41
|
private onShutdown?;
|
|
@@ -61,6 +63,8 @@ export declare class BackgroundManager {
|
|
|
61
63
|
onShutdown?: () => void;
|
|
62
64
|
enableParentSessionNotifications?: boolean;
|
|
63
65
|
handoffCompression?: DcpHandoffCompression;
|
|
66
|
+
/** Full plugin config — supplies `tasks.*` (store location, stale window) to the gates. */
|
|
67
|
+
pluginConfig?: Partial<MatrixxConfig>;
|
|
64
68
|
});
|
|
65
69
|
/**
|
|
66
70
|
* Persist a lightweight handle for the given task. Called on running and
|
|
@@ -138,7 +142,6 @@ export declare class BackgroundManager {
|
|
|
138
142
|
sessionID: string;
|
|
139
143
|
terminalReason?: string;
|
|
140
144
|
}>;
|
|
141
|
-
private checkSessionTodos;
|
|
142
145
|
handleEvent(event: Event): void;
|
|
143
146
|
markForNotification(task: BackgroundTask): void;
|
|
144
147
|
getPendingNotifications(sessionID: string): BackgroundTask[];
|
|
@@ -22,12 +22,19 @@ export interface ReconcileProbeClient {
|
|
|
22
22
|
export interface ReconcileDeps {
|
|
23
23
|
validateOutput?: (sessionID: string) => Promise<boolean>;
|
|
24
24
|
sleep?: (ms: number) => Promise<void>;
|
|
25
|
+
/**
|
|
26
|
+
* Does this session still have pending work in the file-backed task store?
|
|
27
|
+
* Strictly session-scoped: an unrelated session's open task must not keep a
|
|
28
|
+
* restored handle running. Optional — absent means "no pending work".
|
|
29
|
+
*/
|
|
30
|
+
hasPendingTaskWork?: (sessionID: string) => Promise<boolean>;
|
|
25
31
|
}
|
|
26
32
|
/**
|
|
27
33
|
* Classify a persisted `running|pending` handle against the live host.
|
|
28
34
|
*
|
|
29
35
|
* Deterministic order: unprobeable → uncertain; non-idle → running; recorded
|
|
30
36
|
* error → error; awaiting-user → running; no output → stopped; output with
|
|
31
|
-
*
|
|
37
|
+
* pending task-store work in this session → running; otherwise completed.
|
|
38
|
+
* Never throws.
|
|
32
39
|
*/
|
|
33
40
|
export declare function reconcileHandle(client: ReconcileProbeClient, handle: BgHandle, deps?: ReconcileDeps): Promise<ReconcileOutcome>;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
export declare const HANDOFF_TEMPLATE = "# Handoff Command\n\n## Purpose\n\nUse /handoff when:\n- The current session context is getting too long and quality is degrading\n- You want to start fresh while preserving essential context from this session\n- The context window is approaching capacity\n\nThis creates a detailed context summary written to .matrixx/handoff.md. The next session loads it via /pickup.\n\n---\n\n# PHASE 0: VALIDATE REQUEST\n\nBefore proceeding, confirm:\n- [ ] There is meaningful work or context in this session to preserve\n- [ ] The user wants to create a handoff summary (not just asking about it)\n\nIf the session is nearly empty or has no meaningful context, inform the user there is nothing substantial to hand off.\n\n---\n\n# PHASE 1: GATHER PROGRAMMATIC CONTEXT\n\nExecute these tools to gather concrete data:\n\n1. session_read({ session_id: \"$SESSION_ID\" }) \u2014 full session history\n2.
|
|
1
|
+
export declare const HANDOFF_TEMPLATE = "# Handoff Command\n\n## Purpose\n\nUse /handoff when:\n- The current session context is getting too long and quality is degrading\n- You want to start fresh while preserving essential context from this session\n- The context window is approaching capacity\n\nThis creates a detailed context summary written to .matrixx/handoff.md. The next session loads it via /pickup.\n\n---\n\n# PHASE 0: VALIDATE REQUEST\n\nBefore proceeding, confirm:\n- [ ] There is meaningful work or context in this session to preserve\n- [ ] The user wants to create a handoff summary (not just asking about it)\n\nIf the session is nearly empty or has no meaningful context, inform the user there is nothing substantial to hand off.\n\n---\n\n# PHASE 1: GATHER PROGRAMMATIC CONTEXT\n\nExecute these tools to gather concrete data:\n\n1. session_read({ session_id: \"$SESSION_ID\" }) \u2014 full session history\n2. task_list() \u2014 current task progress\n3. Bash({ command: \"git diff --stat HEAD~10..HEAD\" }) \u2014 recent file changes\n4. Bash({ command: \"git status --porcelain\" }) \u2014 uncommitted changes\n\nAnalyze the gathered outputs to understand:\n- What the user asked for (exact wording)\n- What work was completed\n- What tasks remain incomplete\n- What decisions were made\n- What files were modified or discussed\n- What patterns, constraints, or preferences were established\n\n---\n\n# PHASE 2: CALL HANDOFF TOOL\n\nCall the `handoff` tool with `action=\"create\"` and the data you gathered. The tool validates the input and writes the handoff file automatically \u2014 no manual file writing needed.\n\nUse these field mappings for the tool arguments:\n\n```\nhandoff({\n action: \"create\",\n topics: [\"tag1\", \"tag2\"], // Min 1 topic tag, from session context\n user_requests: \"verbatim user msg\", // REQUIRED \u2014 exact wording from session_read\n goal: \"single sentence\", // REQUIRED \u2014 what should be done next\n work_completed: [\"did X\", \"did Y\"], // REQUIRED \u2014 first-person bullet points\n current_state: \"state description\", // REQUIRED \u2014 current codebase/task state\n pending_tasks: [\"task1\", \"task2\"], // Optional \u2014 tasks not yet completed\n key_files: [{path, purpose}], // Optional \u2014 max 10, workspace-relative paths\n important_decisions: [{decision, rationale}], // Optional \u2014 key decisions made\n explicit_constraints: [\"verbatim\"], // Optional \u2014 verbatim constraints only\n context_for_continuation: \"...\" // Optional \u2014 additional context\n})\n```\n\n---\n\n# PHASE 3: INFORM USER\n\nAfter the tool call completes, inform the user:\n\n```\nHandoff saved to .matrixx/handoff.md. Use /pickup in a new opencode session to load this context.\n```\n\n---\n\n# IMPORTANT CONSTRAINTS\n\n- DO gather programmatic context before calling the tool (Phase 1 is mandatory)\n- DO extract user_requests verbatim from session_read output (do not paraphrase)\n- DO keep goal to a single sentence\n- DO use workspace-relative paths for key_files\n- DO NOT attempt to create new sessions programmatically\n- DO NOT exceed 10 files in key_files (max 10)\n- DO NOT include sensitive information (API keys, credentials, secrets)\n- DO use first person perspective for work_completed items\n- DO use plain text with bullets for descriptions (no markdown headers)\n";
|
|
@@ -1 +1 @@
|
|
|
1
|
-
export declare const INIT_DEEP_TEMPLATE = "# /init-deep\n\nGenerate hierarchical AGENTS.md files. Root + complexity-scored subdirectories.\n\n## Usage\n\n```\n/init-deep # Update mode: modify existing + create new where warranted\n/init-deep --create-new # Read existing \u2192 remove all \u2192 regenerate from scratch\n/init-deep --max-depth=2 # Limit directory depth (default: 3)\n```\n\n---\n\n## Workflow (High-Level)\n\n1. **Discovery + Analysis** (concurrent)\n - Fire background explore agents immediately\n - Main session: bash structure + LSP codemap + read existing AGENTS.md\n2. **Score & Decide** - Determine AGENTS.md locations from merged findings\n3. **Generate** - Root first, then subdirs in parallel\n4. **Review** - Deduplicate, trim, validate\n\n<critical>\n**TodoWrite ALL phases. Mark in_progress \u2192 completed in real-time.**\n```\nTodoWrite([\n { id: \"discovery\", content: \"Fire explore agents + LSP codemap + read existing\", status: \"pending\", priority: \"high\" },\n { id: \"scoring\", content: \"Score directories, determine locations\", status: \"pending\", priority: \"high\" },\n { id: \"generate\", content: \"Generate AGENTS.md files (root + subdirs)\", status: \"pending\", priority: \"high\" },\n { id: \"review\", content: \"Deduplicate, validate, trim\", status: \"pending\", priority: \"medium\" }\n])\n```\n</critical>\n\n---\n\n## Phase 1: Discovery + Analysis (Concurrent)\n\n**Mark \"discovery\" as in_progress.**\n\n### Fire Background Explore Agents IMMEDIATELY\n\nDon't wait\u2014these run async while main session works.\n\n```\n// Fire all at once, collect results later\ntask(subagent_type=\"trinity\", load_skills=[], description=\"Explore project structure\", run_in_background=true, prompt=\"Project structure: PREDICT standard patterns for detected language \u2192 REPORT deviations only\")\ntask(subagent_type=\"trinity\", load_skills=[], description=\"Find entry points\", run_in_background=true, prompt=\"Entry points: FIND main files \u2192 REPORT non-standard organization\")\ntask(subagent_type=\"trinity\", load_skills=[], description=\"Find conventions\", run_in_background=true, prompt=\"Conventions: FIND config files (.eslintrc, pyproject.toml, .editorconfig) \u2192 REPORT project-specific rules\")\ntask(subagent_type=\"trinity\", load_skills=[], description=\"Find anti-patterns\", run_in_background=true, prompt=\"Anti-patterns: FIND 'DO NOT', 'NEVER', 'ALWAYS', 'DEPRECATED' comments \u2192 LIST forbidden patterns\")\ntask(subagent_type=\"trinity\", load_skills=[], description=\"Explore build/CI\", run_in_background=true, prompt=\"Build/CI: FIND .github/workflows, Makefile \u2192 REPORT non-standard patterns\")\ntask(subagent_type=\"trinity\", load_skills=[], description=\"Find test patterns\", run_in_background=true, prompt=\"Test patterns: FIND test configs, test structure \u2192 REPORT unique conventions\")\n```\n\n<dynamic-agents>\n**DYNAMIC AGENT SPAWNING**: After bash analysis, spawn ADDITIONAL explore agents based on project scale:\n\n| Factor | Threshold | Additional Agents |\n|--------|-----------|-------------------|\n| **Total files** | >100 | +1 per 100 files |\n| **Total lines** | >10k | +1 per 10k lines |\n| **Directory depth** | \u22654 | +2 for deep exploration |\n| **Large files (>500 lines)** | >10 files | +1 for complexity hotspots |\n| **Monorepo** | detected | +1 per package/workspace |\n| **Multiple languages** | >1 | +1 per language |\n\n```bash\n# Measure project scale first\ntotal_files=$(find . -type f -not -path '*/node_modules/*' -not -path '*/.git/*' | wc -l)\ntotal_lines=$(find . -type f \\( -name \"*.ts\" -o -name \"*.py\" -o -name \"*.go\" \\) -not -path '*/node_modules/*' -exec wc -l {} + 2>/dev/null | tail -1 | awk '{print $1}')\nlarge_files=$(find . -type f \\( -name \"*.ts\" -o -name \"*.py\" \\) -not -path '*/node_modules/*' -exec wc -l {} + 2>/dev/null | awk '$1 > 500 {count++} END {print count+0}')\nmax_depth=$(find . -type d -not -path '*/node_modules/*' -not -path '*/.git/*' | awk -F/ '{print NF}' | sort -rn | head -1)\n```\n\nExample spawning:\n```\n// 500 files, 50k lines, depth 6, 15 large files \u2192 spawn 5+5+2+1 = 13 additional agents\ntask(subagent_type=\"trinity\", load_skills=[], description=\"Analyze large files\", run_in_background=true, prompt=\"Large file analysis: FIND files >500 lines, REPORT complexity hotspots\")\ntask(subagent_type=\"trinity\", load_skills=[], description=\"Explore deep modules\", run_in_background=true, prompt=\"Deep modules at depth 4+: FIND hidden patterns, internal conventions\")\ntask(subagent_type=\"trinity\", load_skills=[], description=\"Find shared utilities\", run_in_background=true, prompt=\"Cross-cutting concerns: FIND shared utilities across directories\")\n// ... more based on calculation\n```\n</dynamic-agents>\n\n### Main Session: Concurrent Analysis\n\n**While background agents run**, main session does:\n\n#### 1. Bash Structural Analysis\n```bash\n# Directory depth + file counts\nfind . -type d -not -path '*/\\.*' -not -path '*/node_modules/*' -not -path '*/venv/*' -not -path '*/dist/*' -not -path '*/build/*' | awk -F/ '{print NF-1}' | sort -n | uniq -c\n\n# Files per directory (top 30)\nfind . -type f -not -path '*/\\.*' -not -path '*/node_modules/*' | sed 's|/[^/]*$||' | sort | uniq -c | sort -rn | head -30\n\n# Code concentration by extension\nfind . -type f \\( -name \"*.py\" -o -name \"*.ts\" -o -name \"*.tsx\" -o -name \"*.js\" -o -name \"*.go\" -o -name \"*.rs\" \\) -not -path '*/node_modules/*' | sed 's|/[^/]*$||' | sort | uniq -c | sort -rn | head -20\n\n# Existing AGENTS.md / CLAUDE.md\nfind . -type f \\( -name \"AGENTS.md\" -o -name \"CLAUDE.md\" \\) -not -path '*/node_modules/*' 2>/dev/null\n```\n\n#### 2. Read Existing AGENTS.md\n```\nFor each existing file found:\n Read(filePath=file)\n Extract: key insights, conventions, anti-patterns\n Store in EXISTING_AGENTS map\n```\n\nIf `--create-new`: Read all existing first (preserve context) \u2192 then delete all \u2192 regenerate.\n\n#### 3. LSP Codemap (if available)\n```\nLspServers() # Check availability\n\n# Entry points (parallel)\nLspDocumentSymbols(filePath=\"src/index.ts\")\nLspDocumentSymbols(filePath=\"main.py\")\n\n# Key symbols (parallel)\nLspWorkspaceSymbols(filePath=\".\", query=\"class\")\nLspWorkspaceSymbols(filePath=\".\", query=\"interface\")\nLspWorkspaceSymbols(filePath=\".\", query=\"function\")\n\n# Centrality for top exports\nLspFindReferences(filePath=\"...\", line=X, character=Y)\n```\n\n**LSP Fallback**: If unavailable, rely on explore agents + AST-grep.\n\n### Collect Background Results\n\n```\n// After main session analysis done, collect all task results\nfor each task_id: background_output(task_id=\"...\")\n```\n\n**Merge: bash + LSP + existing + explore findings. Mark \"discovery\" as completed.**\n\n---\n\n## Phase 2: Scoring & Location Decision\n\n**Mark \"scoring\" as in_progress.**\n\n### Scoring Matrix\n\n| Factor | Weight | High Threshold | Source |\n|--------|--------|----------------|--------|\n| File count | 3x | >20 | bash |\n| Subdir count | 2x | >5 | bash |\n| Code ratio | 2x | >70% | bash |\n| Unique patterns | 1x | Has own config | explore |\n| Module boundary | 2x | Has index.ts/__init__.py | bash |\n| Symbol density | 2x | >30 symbols | LSP |\n| Export count | 2x | >10 exports | LSP |\n| Reference centrality | 3x | >20 refs | LSP |\n\n### Decision Rules\n\n| Score | Action |\n|-------|--------|\n| **Root (.)** | ALWAYS create |\n| **>15** | Create AGENTS.md |\n| **8-15** | Create if distinct domain |\n| **<8** | Skip (parent covers) |\n\n### Output\n```\nAGENTS_LOCATIONS = [\n { path: \".\", type: \"root\" },\n { path: \"src/hooks\", score: 18, reason: \"high complexity\" },\n { path: \"src/api\", score: 12, reason: \"distinct domain\" }\n]\n```\n\n**Mark \"scoring\" as completed.**\n\n---\n\n## Phase 3: Generate AGENTS.md\n\n**Mark \"generate\" as in_progress.**\n\n<critical>\n**File Writing Rule**: If AGENTS.md already exists at the target path \u2192 use `Edit` tool. If it does NOT exist \u2192 use `Write` tool.\nNEVER use Write to overwrite an existing file. ALWAYS check existence first via `Read` or discovery results.\n</critical>\n\n### Root AGENTS.md (Full Treatment)\n\n```markdown\n# PROJECT KNOWLEDGE BASE\n\n**Generated:** {TIMESTAMP}\n**Commit:** {SHORT_SHA}\n**Branch:** {BRANCH}\n\n## OVERVIEW\n{1-2 sentences: what + core stack}\n\n## STRUCTURE\n\\`\\`\\`\n{root}/\n\u251C\u2500\u2500 {dir}/ # {non-obvious purpose only}\n\u2514\u2500\u2500 {entry}\n\\`\\`\\`\n\n## WHERE TO LOOK\n| Task | Location | Notes |\n|------|----------|-------|\n\n## CODE MAP\n{From LSP - skip if unavailable or project <10 files}\n\n| Symbol | Type | Location | Refs | Role |\n|--------|------|----------|------|------|\n\n## CONVENTIONS\n{ONLY deviations from standard}\n\n## ANTI-PATTERNS (THIS PROJECT)\n{Explicitly forbidden here}\n\n## UNIQUE STYLES\n{Project-specific}\n\n## COMMANDS\n\\`\\`\\`bash\n{dev/test/build}\n\\`\\`\\`\n\n## NOTES\n{Gotchas}\n```\n\n**Quality gates**: 50-150 lines, no generic advice, no obvious info.\n\n### Subdirectory AGENTS.md (Parallel)\n\nLaunch writing tasks for each location:\n\n```\nfor loc in AGENTS_LOCATIONS (except root):\n task(category=\"broadcast\", load_skills=[], run_in_background=false, description=\"Generate AGENTS.md\", prompt=\\`\n Generate AGENTS.md for: ${loc.path}\n - Reason: ${loc.reason}\n - 30-80 lines max\n - NEVER repeat parent content\n - Sections: OVERVIEW (1 line), STRUCTURE (if >5 subdirs), WHERE TO LOOK, CONVENTIONS (if different), ANTI-PATTERNS\n \\`)\n```\n\n**Wait for all. Mark \"generate\" as completed.**\n\n---\n\n## Phase 4: Review & Deduplicate\n\n**Mark \"review\" as in_progress.**\n\nFor each generated file:\n- Remove generic advice\n- Remove parent duplicates\n- Trim to size limits\n- Verify telegraphic style\n\n**Mark \"review\" as completed.**\n\n---\n\n## Final Report\n\n```\n=== init-deep Complete ===\n\nMode: {update | create-new}\n\nFiles:\n [OK] ./AGENTS.md (root, {N} lines)\n [OK] ./src/hooks/AGENTS.md ({N} lines)\n\nDirs Analyzed: {N}\nAGENTS.md Created: {N}\nAGENTS.md Updated: {N}\n\nHierarchy:\n ./AGENTS.md\n \u2514\u2500\u2500 src/hooks/AGENTS.md\n```\n\n---\n\n## Anti-Patterns\n\n- **Static agent count**: MUST vary agents based on project size/depth\n- **Sequential execution**: MUST parallel (explore + LSP concurrent)\n- **Ignoring existing**: ALWAYS read existing first, even with --create-new\n- **Over-documenting**: Not every dir needs AGENTS.md\n- **Redundancy**: Child never repeats parent\n- **Generic content**: Remove anything that applies to ALL projects\n- **Verbose style**: Telegraphic or die";
|
|
1
|
+
export declare const INIT_DEEP_TEMPLATE = "# /init-deep\n\nGenerate hierarchical AGENTS.md files. Root + complexity-scored subdirectories.\n\n## Usage\n\n```\n/init-deep # Update mode: modify existing + create new where warranted\n/init-deep --create-new # Read existing \u2192 remove all \u2192 regenerate from scratch\n/init-deep --max-depth=2 # Limit directory depth (default: 3)\n```\n\n---\n\n## Workflow (High-Level)\n\n1. **Discovery + Analysis** (concurrent)\n - Fire background explore agents immediately\n - Main session: bash structure + LSP codemap + read existing AGENTS.md\n2. **Score & Decide** - Determine AGENTS.md locations from merged findings\n3. **Generate** - Root first, then subdirs in parallel\n4. **Review** - Deduplicate, trim, validate\n\n<critical>\n**task_create ALL phases. Mark in_progress \u2192 completed in real-time.**\n```\ntask_create({ items: [\n { subject: \"discovery\", priority: \"high\", description: \"Fire explore agents + LSP codemap + read existing\" },\n { subject: \"scoring\", priority: \"high\", description: \"Score directories, determine locations\" },\n { subject: \"generate\", priority: \"high\", description: \"Generate AGENTS.md files (root + subdirs)\" },\n { subject: \"review\", priority: \"medium\", description: \"Deduplicate, validate, trim\" }\n]})\n```\n</critical>\n\n---\n\n## Phase 1: Discovery + Analysis (Concurrent)\n\n**Mark \"discovery\" as in_progress.**\n\n### Fire Background Explore Agents IMMEDIATELY\n\nDon't wait\u2014these run async while main session works.\n\n```\n// Fire all at once, collect results later\ntask(subagent_type=\"trinity\", load_skills=[], description=\"Explore project structure\", run_in_background=true, prompt=\"Project structure: PREDICT standard patterns for detected language \u2192 REPORT deviations only\")\ntask(subagent_type=\"trinity\", load_skills=[], description=\"Find entry points\", run_in_background=true, prompt=\"Entry points: FIND main files \u2192 REPORT non-standard organization\")\ntask(subagent_type=\"trinity\", load_skills=[], description=\"Find conventions\", run_in_background=true, prompt=\"Conventions: FIND config files (.eslintrc, pyproject.toml, .editorconfig) \u2192 REPORT project-specific rules\")\ntask(subagent_type=\"trinity\", load_skills=[], description=\"Find anti-patterns\", run_in_background=true, prompt=\"Anti-patterns: FIND 'DO NOT', 'NEVER', 'ALWAYS', 'DEPRECATED' comments \u2192 LIST forbidden patterns\")\ntask(subagent_type=\"trinity\", load_skills=[], description=\"Explore build/CI\", run_in_background=true, prompt=\"Build/CI: FIND .github/workflows, Makefile \u2192 REPORT non-standard patterns\")\ntask(subagent_type=\"trinity\", load_skills=[], description=\"Find test patterns\", run_in_background=true, prompt=\"Test patterns: FIND test configs, test structure \u2192 REPORT unique conventions\")\n```\n\n<dynamic-agents>\n**DYNAMIC AGENT SPAWNING**: After bash analysis, spawn ADDITIONAL explore agents based on project scale:\n\n| Factor | Threshold | Additional Agents |\n|--------|-----------|-------------------|\n| **Total files** | >100 | +1 per 100 files |\n| **Total lines** | >10k | +1 per 10k lines |\n| **Directory depth** | \u22654 | +2 for deep exploration |\n| **Large files (>500 lines)** | >10 files | +1 for complexity hotspots |\n| **Monorepo** | detected | +1 per package/workspace |\n| **Multiple languages** | >1 | +1 per language |\n\n```bash\n# Measure project scale first\ntotal_files=$(find . -type f -not -path '*/node_modules/*' -not -path '*/.git/*' | wc -l)\ntotal_lines=$(find . -type f \\( -name \"*.ts\" -o -name \"*.py\" -o -name \"*.go\" \\) -not -path '*/node_modules/*' -exec wc -l {} + 2>/dev/null | tail -1 | awk '{print $1}')\nlarge_files=$(find . -type f \\( -name \"*.ts\" -o -name \"*.py\" \\) -not -path '*/node_modules/*' -exec wc -l {} + 2>/dev/null | awk '$1 > 500 {count++} END {print count+0}')\nmax_depth=$(find . -type d -not -path '*/node_modules/*' -not -path '*/.git/*' | awk -F/ '{print NF}' | sort -rn | head -1)\n```\n\nExample spawning:\n```\n// 500 files, 50k lines, depth 6, 15 large files \u2192 spawn 5+5+2+1 = 13 additional agents\ntask(subagent_type=\"trinity\", load_skills=[], description=\"Analyze large files\", run_in_background=true, prompt=\"Large file analysis: FIND files >500 lines, REPORT complexity hotspots\")\ntask(subagent_type=\"trinity\", load_skills=[], description=\"Explore deep modules\", run_in_background=true, prompt=\"Deep modules at depth 4+: FIND hidden patterns, internal conventions\")\ntask(subagent_type=\"trinity\", load_skills=[], description=\"Find shared utilities\", run_in_background=true, prompt=\"Cross-cutting concerns: FIND shared utilities across directories\")\n// ... more based on calculation\n```\n</dynamic-agents>\n\n### Main Session: Concurrent Analysis\n\n**While background agents run**, main session does:\n\n#### 1. Bash Structural Analysis\n```bash\n# Directory depth + file counts\nfind . -type d -not -path '*/\\.*' -not -path '*/node_modules/*' -not -path '*/venv/*' -not -path '*/dist/*' -not -path '*/build/*' | awk -F/ '{print NF-1}' | sort -n | uniq -c\n\n# Files per directory (top 30)\nfind . -type f -not -path '*/\\.*' -not -path '*/node_modules/*' | sed 's|/[^/]*$||' | sort | uniq -c | sort -rn | head -30\n\n# Code concentration by extension\nfind . -type f \\( -name \"*.py\" -o -name \"*.ts\" -o -name \"*.tsx\" -o -name \"*.js\" -o -name \"*.go\" -o -name \"*.rs\" \\) -not -path '*/node_modules/*' | sed 's|/[^/]*$||' | sort | uniq -c | sort -rn | head -20\n\n# Existing AGENTS.md / CLAUDE.md\nfind . -type f \\( -name \"AGENTS.md\" -o -name \"CLAUDE.md\" \\) -not -path '*/node_modules/*' 2>/dev/null\n```\n\n#### 2. Read Existing AGENTS.md\n```\nFor each existing file found:\n Read(filePath=file)\n Extract: key insights, conventions, anti-patterns\n Store in EXISTING_AGENTS map\n```\n\nIf `--create-new`: Read all existing first (preserve context) \u2192 then delete all \u2192 regenerate.\n\n#### 3. LSP Codemap (if available)\n```\nLspServers() # Check availability\n\n# Entry points (parallel)\nLspDocumentSymbols(filePath=\"src/index.ts\")\nLspDocumentSymbols(filePath=\"main.py\")\n\n# Key symbols (parallel)\nLspWorkspaceSymbols(filePath=\".\", query=\"class\")\nLspWorkspaceSymbols(filePath=\".\", query=\"interface\")\nLspWorkspaceSymbols(filePath=\".\", query=\"function\")\n\n# Centrality for top exports\nLspFindReferences(filePath=\"...\", line=X, character=Y)\n```\n\n**LSP Fallback**: If unavailable, rely on explore agents + AST-grep.\n\n### Collect Background Results\n\n```\n// After main session analysis done, collect all task results\nfor each task_id: background_output(task_id=\"...\")\n```\n\n**Merge: bash + LSP + existing + explore findings. Mark \"discovery\" as completed.**\n\n---\n\n## Phase 2: Scoring & Location Decision\n\n**Mark \"scoring\" as in_progress.**\n\n### Scoring Matrix\n\n| Factor | Weight | High Threshold | Source |\n|--------|--------|----------------|--------|\n| File count | 3x | >20 | bash |\n| Subdir count | 2x | >5 | bash |\n| Code ratio | 2x | >70% | bash |\n| Unique patterns | 1x | Has own config | explore |\n| Module boundary | 2x | Has index.ts/__init__.py | bash |\n| Symbol density | 2x | >30 symbols | LSP |\n| Export count | 2x | >10 exports | LSP |\n| Reference centrality | 3x | >20 refs | LSP |\n\n### Decision Rules\n\n| Score | Action |\n|-------|--------|\n| **Root (.)** | ALWAYS create |\n| **>15** | Create AGENTS.md |\n| **8-15** | Create if distinct domain |\n| **<8** | Skip (parent covers) |\n\n### Output\n```\nAGENTS_LOCATIONS = [\n { path: \".\", type: \"root\" },\n { path: \"src/hooks\", score: 18, reason: \"high complexity\" },\n { path: \"src/api\", score: 12, reason: \"distinct domain\" }\n]\n```\n\n**Mark \"scoring\" as completed.**\n\n---\n\n## Phase 3: Generate AGENTS.md\n\n**Mark \"generate\" as in_progress.**\n\n<critical>\n**File Writing Rule**: If AGENTS.md already exists at the target path \u2192 use `Edit` tool. If it does NOT exist \u2192 use `Write` tool.\nNEVER use Write to overwrite an existing file. ALWAYS check existence first via `Read` or discovery results.\n</critical>\n\n### Root AGENTS.md (Full Treatment)\n\n```markdown\n# PROJECT KNOWLEDGE BASE\n\n**Generated:** {TIMESTAMP}\n**Commit:** {SHORT_SHA}\n**Branch:** {BRANCH}\n\n## OVERVIEW\n{1-2 sentences: what + core stack}\n\n## STRUCTURE\n\\`\\`\\`\n{root}/\n\u251C\u2500\u2500 {dir}/ # {non-obvious purpose only}\n\u2514\u2500\u2500 {entry}\n\\`\\`\\`\n\n## WHERE TO LOOK\n| Task | Location | Notes |\n|------|----------|-------|\n\n## CODE MAP\n{From LSP - skip if unavailable or project <10 files}\n\n| Symbol | Type | Location | Refs | Role |\n|--------|------|----------|------|------|\n\n## CONVENTIONS\n{ONLY deviations from standard}\n\n## ANTI-PATTERNS (THIS PROJECT)\n{Explicitly forbidden here}\n\n## UNIQUE STYLES\n{Project-specific}\n\n## COMMANDS\n\\`\\`\\`bash\n{dev/test/build}\n\\`\\`\\`\n\n## NOTES\n{Gotchas}\n```\n\n**Quality gates**: 50-150 lines, no generic advice, no obvious info.\n\n### Subdirectory AGENTS.md (Parallel)\n\nLaunch writing tasks for each location:\n\n```\nfor loc in AGENTS_LOCATIONS (except root):\n task(category=\"broadcast\", load_skills=[], run_in_background=false, description=\"Generate AGENTS.md\", prompt=\\`\n Generate AGENTS.md for: ${loc.path}\n - Reason: ${loc.reason}\n - 30-80 lines max\n - NEVER repeat parent content\n - Sections: OVERVIEW (1 line), STRUCTURE (if >5 subdirs), WHERE TO LOOK, CONVENTIONS (if different), ANTI-PATTERNS\n \\`)\n```\n\n**Wait for all. Mark \"generate\" as completed.**\n\n---\n\n## Phase 4: Review & Deduplicate\n\n**Mark \"review\" as in_progress.**\n\nFor each generated file:\n- Remove generic advice\n- Remove parent duplicates\n- Trim to size limits\n- Verify telegraphic style\n\n**Mark \"review\" as completed.**\n\n---\n\n## Final Report\n\n```\n=== init-deep Complete ===\n\nMode: {update | create-new}\n\nFiles:\n [OK] ./AGENTS.md (root, {N} lines)\n [OK] ./src/hooks/AGENTS.md ({N} lines)\n\nDirs Analyzed: {N}\nAGENTS.md Created: {N}\nAGENTS.md Updated: {N}\n\nHierarchy:\n ./AGENTS.md\n \u2514\u2500\u2500 src/hooks/AGENTS.md\n```\n\n---\n\n## Anti-Patterns\n\n- **Static agent count**: MUST vary agents based on project size/depth\n- **Sequential execution**: MUST parallel (explore + LSP concurrent)\n- **Ignoring existing**: ALWAYS read existing first, even with --create-new\n- **Over-documenting**: Not every dir needs AGENTS.md\n- **Redundancy**: Child never repeats parent\n- **Generic content**: Remove anything that applies to ALL projects\n- **Verbose style**: Telegraphic or die";
|
|
@@ -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 `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
|
+
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```\ntask_create({ items: [\n {\"subject\": \"PHASE 1: Codebase Analysis - launch parallel explore agents\", \"priority\": \"high\"},\n {\"subject\": \"PHASE 2: Build Codemap - map dependencies and impact zones\", \"priority\": \"high\"},\n {\"subject\": \"PHASE 3: Test Assessment - analyze test coverage and verification strategy\", \"priority\": \"high\"},\n {\"subject\": \"PHASE 4: Plan Generation - invoke Plan agent for detailed refactoring plan\", \"priority\": \"high\"},\n {\"subject\": \"PHASE 5: Execute Refactoring - step-by-step with continuous verification\", \"priority\": \"high\"},\n {\"subject\": \"PHASE 6: Final Verification - full test suite and regression check\", \"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```\ntask_create({ items: [\n // Each step from the plan becomes a task\n {\"subject\": \"Step 1: [description]\", \"priority\": \"high\"},\n {\"subject\": \"Verify Step 1: run tests\", \"priority\": \"high\"},\n {\"subject\": \"Step 2: [description]\", \"priority\": \"medium\"},\n {\"subject\": \"Verify Step 2: run tests\", \"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 +1 @@
|
|
|
1
|
-
export declare const REMOVE_DEADCODE_TEMPLATE = "# Remove Dead Code Command\n\n## Usage\n```\n/remove-deadcode [target-path] [--scope=<file|module|project>] [--dry-run]\n\nArguments:\n target-path: Where to scan for dead code. Can be:\n - File path: src/auth/handler.ts\n - Directory: src/features/\n - Glob: src/**/*.ts\n - Omitted: defaults to current project src/\n\nOptions:\n --scope: Scanning scope (default: module)\n - file: Single file only\n - module: Module/directory and its dependents\n - project: Entire codebase\n\n --dry-run: Report dead code without removing it (default: false)\n```\n\n## What This Command Does\n\nFinds and removes dead code (zero-reference symbols) using LSP analysis. Unlike grep-based approaches, this uses semantic understanding:\n\n1. **Discovers symbols** - Uses LSP to enumerate all exported and internal symbols\n2. **Counts references** - Uses LspFindReferences to find actual usage sites\n3. **Classifies confidence** - Categorizes findings by removal safety\n4. **Reports findings** - Presents dead code organized by confidence level\n5. **Removes safely** - Deletes confirmed dead code with continuous verification\n6. **Verifies integrity** - Runs build and tests after each removal batch\n\n---\n\n# PHASE 0: VALIDATE REQUEST (MANDATORY FIRST STEP)\n\n## Step 0.1: Parse Target\n\n| Input | Interpretation |\n|-------|---------------|\n| File path | Scan that file only |\n| Directory path | Scan all source files in directory |\n| Glob pattern | Scan matching files |\n| No argument | Scan project src/ directory |\n\n## Step 0.2: Detect --dry-run Flag\n\nIf --dry-run is present or user says \"just show me\" / \"report only\":\n- Set dry-run mode: report findings WITHOUT removing anything\n- Skip PHASE 4 (removal) entirely\n\n## Step 0.3: Create Initial Todos\n\n```\nTodoWrite([\n {\"content\": \"PHASE 1: Symbol Discovery - enumerate all symbols via LSP\", \"status\": \"pending\", \"priority\": \"high\"},\n {\"content\": \"PHASE 2: Reference Analysis - find references for each symbol\", \"status\": \"pending\", \"priority\": \"high\"},\n {\"content\": \"PHASE 3: Dead Code Report - classify and present findings\", \"status\": \"pending\", \"priority\": \"high\"},\n {\"content\": \"PHASE 4: Safe Removal - remove confirmed dead code with verification\", \"status\": \"pending\", \"priority\": \"high\"},\n {\"content\": \"PHASE 5: Final Verification - build and test suite\", \"status\": \"pending\", \"priority\": \"high\"}\n])\n```\n\n---\n\n# PHASE 1: SYMBOL DISCOVERY\n\n**Mark PHASE 1 as in_progress.**\n\n## 1.1: Enumerate Source Files\n\nDetermine the set of files to scan based on target:\n\n```typescript\n// For a single file\nLspDocumentSymbols(filePath)\n\n// For a directory, use Glob to find all source files first\nGlob(pattern=\"**/*.ts\", path=\"[target-directory]\")\n// Then LspDocumentSymbols for each file\n```\n\n## 1.2: Collect All Symbols\n\nFor each source file, gather:\n- Function declarations (named functions, arrow functions assigned to const)\n- Class declarations\n- Interface and type alias declarations\n- Enum declarations\n- Variable declarations (const/let at module scope)\n- Method declarations (within classes)\n\nUse `LspDocumentSymbols(filePath)` to get the hierarchical symbol outline.\n\n## 1.3: Filter Symbol Candidates\n\n**SKIP these symbols (never flag as dead):**\n- Symbols in index.ts / barrel files (re-exports)\n- Symbols with `export default`\n- Entry point files (main, index, plugin entry)\n- Test files (`*.test.ts`, `*.spec.ts`)\n- Symbols starting with `_` (conventionally private/internal)\n- Type-only exports used in declaration files\n\n**INCLUDE these symbols:**\n- Non-exported functions/classes/types within a module\n- Exported symbols that may have zero consumers\n- Private class methods and properties\n\n**Mark PHASE 1 as completed.**\n\n---\n\n# PHASE 2: REFERENCE ANALYSIS\n\n**Mark PHASE 2 as in_progress.**\n\n## 2.1: Count References Per Symbol\n\nFor each symbol candidate from Phase 1:\n\n```typescript\n// Get all references across the workspace\nLspFindReferences(filePath, line, character, includeDeclaration=false)\n```\n\n**IMPORTANT**: Set `includeDeclaration=false` so the declaration site itself is NOT counted as a reference.\n\n## 2.2: Classify Reference Counts\n\n| References | Classification | Confidence |\n|------------|---------------|------------|\n| 0 external references | Dead code | HIGH - safe to remove |\n| 0 refs, but exported from package index | Possibly dead | MEDIUM - may be used externally |\n| 0 refs, but in a public API file | Possibly dead | LOW - may be part of public contract |\n| 1+ references | Live code | SKIP - do not flag |\n\n## 2.3: Cross-Check with AST-Grep\n\nFor HIGH confidence candidates, verify with AST-Grep to catch dynamic references:\n\n```typescript\n// Check for string-based references (dynamic imports, reflection)\nast_grep_search(\n pattern='\"[symbol-name]\"',\n lang=\"typescript\",\n paths=[\"src/\"]\n)\n\n// Check for computed property access\ngrep(pattern=\"[symbol-name]\", path=\"src/\", include=\"*.ts\")\n```\n\nIf AST-Grep or grep finds string-based references, downgrade confidence from HIGH to MEDIUM.\n\n**Mark PHASE 2 as completed.**\n\n---\n\n# PHASE 3: DEAD CODE REPORT\n\n**Mark PHASE 3 as in_progress.**\n\n## 3.1: Generate Report\n\nPresent findings organized by confidence:\n\n```\n## Dead Code Analysis Report\n\n### Scan Target: [path]\n### Files Scanned: [N]\n### Symbols Analyzed: [N]\n### Dead Code Found: [N] symbols\n\n---\n\n### HIGH Confidence (Safe to Remove)\nThese symbols have zero references anywhere in the codebase.\n\n| # | Symbol | File | Line | Type |\n|---|--------|------|------|------|\n| 1 | unusedHelper | src/utils/helpers.ts | 42 | function |\n| 2 | OldConfig | src/config/legacy.ts | 15 | interface |\n\n### MEDIUM Confidence (Review Required)\nThese symbols appear unused but may have external consumers or dynamic references.\n\n| # | Symbol | File | Line | Type | Reason |\n|---|--------|------|------|------|--------|\n| 1 | exportedUtil | src/shared/utils.ts | 88 | function | exported, no internal refs |\n\n### LOW Confidence (Manual Review)\nThese symbols may be part of a public API or have indirect usage patterns.\n\n| # | Symbol | File | Line | Type | Reason |\n|---|--------|------|------|------|--------|\n| 1 | ApiResponse | src/types/api.ts | 12 | type | public API type |\n```\n\n## 3.2: If --dry-run Mode\n\nPresent the report and STOP. Do not proceed to Phase 4.\n\n```\nThis was a dry-run analysis. No code was modified.\nTo remove dead code, run: /remove-deadcode [same-target]\n```\n\n**Mark PHASE 3 as completed.**\n\n---\n\n# PHASE 4: SAFE REMOVAL\n\n**Mark PHASE 4 as in_progress.**\n\n## 4.1: Removal Strategy\n\n**Remove in order of confidence (HIGH first):**\n\n1. Start with HIGH confidence symbols\n2. After each batch, run verification\n3. Only proceed to MEDIUM confidence if user approves\n4. NEVER auto-remove LOW confidence symbols\n\n## 4.2: Batch Removal Protocol\n\nFor each removal batch:\n\n### Pre-Removal\n1. Read the file to get current state\n2. Run `lsp_diagnostics(filePath)` to establish baseline\n\n### Execute Removal\n```typescript\n// Use Edit tool to remove the dead symbol\n// Remove the entire declaration including JSDoc/comments above it\nedit(filePath, oldString=\"[full-symbol-declaration]\", newString=\"\")\n```\n\n### Post-Removal Verification (MANDATORY)\n```typescript\n// 1. Check diagnostics - no new errors\nlsp_diagnostics(filePath)\n\n// 2. Check imports - remove now-unused imports\n// If removing a symbol makes an import unused, remove the import too\nLspDocumentSymbols(filePath)\n\n// 3. Run type check\nbash(\"tsc --noEmit\")\n\n// 4. Run tests\nbash(\"bun test\")\n```\n\n## 4.3: Cascading Cleanup\n\nAfter removing a symbol, check if its removal creates new dead code:\n- Imports that are now unused\n- Helper functions only called by the removed symbol\n- Types only used by the removed symbol\n\nRemove cascading dead code in the same batch.\n\n## 4.4: MEDIUM Confidence Handling\n\nBefore removing MEDIUM confidence symbols, ask the user:\n\n```\nThe following MEDIUM confidence symbols appear unused but may have external consumers:\n\n1. [symbol] in [file] - [reason for medium confidence]\n\nShould I:\n1. Remove them (I confirm they are unused)\n2. Skip them (keep for now)\n3. Review each one individually\n```\n\n**Mark PHASE 4 as completed.**\n\n---\n\n# PHASE 5: FINAL VERIFICATION\n\n**Mark PHASE 5 as in_progress.**\n\n## 5.1: Full Build Check\n\n```bash\ntsc --noEmit\nbun run build\n```\n\n## 5.2: Full Test Suite\n\n```bash\nbun test\n```\n\n## 5.3: Diagnostics on Changed Files\n\n```typescript\n// Check all files that were modified\nfor (file of modifiedFiles) {\n lsp_diagnostics(file)\n}\n```\n\n## 5.4: Generate Summary\n\n```\n## Dead Code Removal Complete\n\n### Removed\n- [N] HIGH confidence symbols removed\n- [N] MEDIUM confidence symbols removed (user-approved)\n- [N] cascading cleanups (unused imports, helper functions)\n\n### Preserved\n- [N] LOW confidence symbols (manual review needed)\n- [N] MEDIUM confidence symbols (user chose to keep)\n\n### Files Modified\n- \\`path/to/file.ts\\` - removed [symbol1], [symbol2]\n- \\`path/to/file2.ts\\` - removed [symbol3]\n\n### Verification\n- Type Check: PASSED\n- Build: PASSED\n- Tests: PASSED ([X] passing, [Y] pre-existing failures)\n- Diagnostics: CLEAN (no new errors)\n\n### Lines of Code Removed: [N]\n```\n\n**Mark PHASE 5 as completed.**\n\n---\n\n# CRITICAL RULES\n\n## NEVER DO\n- Remove symbols from barrel/index files without checking all consumers\n- Remove exported symbols without checking external package consumers\n- Remove symbols referenced in configuration files, scripts, or non-TS files\n- Skip lsp_diagnostics after removal\n- Proceed with failing tests after removal\n- Remove event handlers, lifecycle hooks, or decorator-referenced symbols\n- Remove symbols used in dependency injection containers\n- Use `as any`, `@ts-ignore`, `@ts-expect-error` to suppress removal side effects\n\n## ALWAYS DO\n- Use LspFindReferences (not grep) as the primary reference detection method\n- Cross-check with grep/AST-Grep for dynamic references\n- Verify build and tests after each removal batch\n- Ask for user confirmation before removing MEDIUM confidence symbols\n- Report LOW confidence findings without auto-removing\n- Clean up cascading dead code (unused imports, orphaned helpers)\n- Keep todos updated in real-time\n\n## ABORT CONDITIONS\nIf any of these occur, STOP and consult user:\n- Build fails after removal\n- Tests fail after removal (new failures, not pre-existing)\n- More than 20 symbols flagged as dead in a single file (likely misconfiguration)\n- Removed symbol is referenced in non-TypeScript files (configs, scripts)\n\n<user-request>\n$ARGUMENTS\n</user-request>\n";
|
|
1
|
+
export declare const REMOVE_DEADCODE_TEMPLATE = "# Remove Dead Code Command\n\n## Usage\n```\n/remove-deadcode [target-path] [--scope=<file|module|project>] [--dry-run]\n\nArguments:\n target-path: Where to scan for dead code. Can be:\n - File path: src/auth/handler.ts\n - Directory: src/features/\n - Glob: src/**/*.ts\n - Omitted: defaults to current project src/\n\nOptions:\n --scope: Scanning scope (default: module)\n - file: Single file only\n - module: Module/directory and its dependents\n - project: Entire codebase\n\n --dry-run: Report dead code without removing it (default: false)\n```\n\n## What This Command Does\n\nFinds and removes dead code (zero-reference symbols) using LSP analysis. Unlike grep-based approaches, this uses semantic understanding:\n\n1. **Discovers symbols** - Uses LSP to enumerate all exported and internal symbols\n2. **Counts references** - Uses LspFindReferences to find actual usage sites\n3. **Classifies confidence** - Categorizes findings by removal safety\n4. **Reports findings** - Presents dead code organized by confidence level\n5. **Removes safely** - Deletes confirmed dead code with continuous verification\n6. **Verifies integrity** - Runs build and tests after each removal batch\n\n---\n\n# PHASE 0: VALIDATE REQUEST (MANDATORY FIRST STEP)\n\n## Step 0.1: Parse Target\n\n| Input | Interpretation |\n|-------|---------------|\n| File path | Scan that file only |\n| Directory path | Scan all source files in directory |\n| Glob pattern | Scan matching files |\n| No argument | Scan project src/ directory |\n\n## Step 0.2: Detect --dry-run Flag\n\nIf --dry-run is present or user says \"just show me\" / \"report only\":\n- Set dry-run mode: report findings WITHOUT removing anything\n- Skip PHASE 4 (removal) entirely\n\n## Step 0.3: Create Initial Todos\n\n```\ntask_create({ items: [\n {\"subject\": \"PHASE 1: Symbol Discovery - enumerate all symbols via LSP\", \"priority\": \"high\"},\n {\"subject\": \"PHASE 2: Reference Analysis - find references for each symbol\", \"priority\": \"high\"},\n {\"subject\": \"PHASE 3: Dead Code Report - classify and present findings\", \"priority\": \"high\"},\n {\"subject\": \"PHASE 4: Safe Removal - remove confirmed dead code with verification\", \"priority\": \"high\"},\n {\"subject\": \"PHASE 5: Final Verification - build and test suite\", \"priority\": \"high\"}\n]})\n```\n\n---\n\n# PHASE 1: SYMBOL DISCOVERY\n\n**Mark PHASE 1 as in_progress.**\n\n## 1.1: Enumerate Source Files\n\nDetermine the set of files to scan based on target:\n\n```typescript\n// For a single file\nLspDocumentSymbols(filePath)\n\n// For a directory, use Glob to find all source files first\nGlob(pattern=\"**/*.ts\", path=\"[target-directory]\")\n// Then LspDocumentSymbols for each file\n```\n\n## 1.2: Collect All Symbols\n\nFor each source file, gather:\n- Function declarations (named functions, arrow functions assigned to const)\n- Class declarations\n- Interface and type alias declarations\n- Enum declarations\n- Variable declarations (const/let at module scope)\n- Method declarations (within classes)\n\nUse `LspDocumentSymbols(filePath)` to get the hierarchical symbol outline.\n\n## 1.3: Filter Symbol Candidates\n\n**SKIP these symbols (never flag as dead):**\n- Symbols in index.ts / barrel files (re-exports)\n- Symbols with `export default`\n- Entry point files (main, index, plugin entry)\n- Test files (`*.test.ts`, `*.spec.ts`)\n- Symbols starting with `_` (conventionally private/internal)\n- Type-only exports used in declaration files\n\n**INCLUDE these symbols:**\n- Non-exported functions/classes/types within a module\n- Exported symbols that may have zero consumers\n- Private class methods and properties\n\n**Mark PHASE 1 as completed.**\n\n---\n\n# PHASE 2: REFERENCE ANALYSIS\n\n**Mark PHASE 2 as in_progress.**\n\n## 2.1: Count References Per Symbol\n\nFor each symbol candidate from Phase 1:\n\n```typescript\n// Get all references across the workspace\nLspFindReferences(filePath, line, character, includeDeclaration=false)\n```\n\n**IMPORTANT**: Set `includeDeclaration=false` so the declaration site itself is NOT counted as a reference.\n\n## 2.2: Classify Reference Counts\n\n| References | Classification | Confidence |\n|------------|---------------|------------|\n| 0 external references | Dead code | HIGH - safe to remove |\n| 0 refs, but exported from package index | Possibly dead | MEDIUM - may be used externally |\n| 0 refs, but in a public API file | Possibly dead | LOW - may be part of public contract |\n| 1+ references | Live code | SKIP - do not flag |\n\n## 2.3: Cross-Check with AST-Grep\n\nFor HIGH confidence candidates, verify with AST-Grep to catch dynamic references:\n\n```typescript\n// Check for string-based references (dynamic imports, reflection)\nast_grep_search(\n pattern='\"[symbol-name]\"',\n lang=\"typescript\",\n paths=[\"src/\"]\n)\n\n// Check for computed property access\ngrep(pattern=\"[symbol-name]\", path=\"src/\", include=\"*.ts\")\n```\n\nIf AST-Grep or grep finds string-based references, downgrade confidence from HIGH to MEDIUM.\n\n**Mark PHASE 2 as completed.**\n\n---\n\n# PHASE 3: DEAD CODE REPORT\n\n**Mark PHASE 3 as in_progress.**\n\n## 3.1: Generate Report\n\nPresent findings organized by confidence:\n\n```\n## Dead Code Analysis Report\n\n### Scan Target: [path]\n### Files Scanned: [N]\n### Symbols Analyzed: [N]\n### Dead Code Found: [N] symbols\n\n---\n\n### HIGH Confidence (Safe to Remove)\nThese symbols have zero references anywhere in the codebase.\n\n| # | Symbol | File | Line | Type |\n|---|--------|------|------|------|\n| 1 | unusedHelper | src/utils/helpers.ts | 42 | function |\n| 2 | OldConfig | src/config/legacy.ts | 15 | interface |\n\n### MEDIUM Confidence (Review Required)\nThese symbols appear unused but may have external consumers or dynamic references.\n\n| # | Symbol | File | Line | Type | Reason |\n|---|--------|------|------|------|--------|\n| 1 | exportedUtil | src/shared/utils.ts | 88 | function | exported, no internal refs |\n\n### LOW Confidence (Manual Review)\nThese symbols may be part of a public API or have indirect usage patterns.\n\n| # | Symbol | File | Line | Type | Reason |\n|---|--------|------|------|------|--------|\n| 1 | ApiResponse | src/types/api.ts | 12 | type | public API type |\n```\n\n## 3.2: If --dry-run Mode\n\nPresent the report and STOP. Do not proceed to Phase 4.\n\n```\nThis was a dry-run analysis. No code was modified.\nTo remove dead code, run: /remove-deadcode [same-target]\n```\n\n**Mark PHASE 3 as completed.**\n\n---\n\n# PHASE 4: SAFE REMOVAL\n\n**Mark PHASE 4 as in_progress.**\n\n## 4.1: Removal Strategy\n\n**Remove in order of confidence (HIGH first):**\n\n1. Start with HIGH confidence symbols\n2. After each batch, run verification\n3. Only proceed to MEDIUM confidence if user approves\n4. NEVER auto-remove LOW confidence symbols\n\n## 4.2: Batch Removal Protocol\n\nFor each removal batch:\n\n### Pre-Removal\n1. Read the file to get current state\n2. Run `lsp_diagnostics(filePath)` to establish baseline\n\n### Execute Removal\n```typescript\n// Use Edit tool to remove the dead symbol\n// Remove the entire declaration including JSDoc/comments above it\nedit(filePath, oldString=\"[full-symbol-declaration]\", newString=\"\")\n```\n\n### Post-Removal Verification (MANDATORY)\n```typescript\n// 1. Check diagnostics - no new errors\nlsp_diagnostics(filePath)\n\n// 2. Check imports - remove now-unused imports\n// If removing a symbol makes an import unused, remove the import too\nLspDocumentSymbols(filePath)\n\n// 3. Run type check\nbash(\"tsc --noEmit\")\n\n// 4. Run tests\nbash(\"bun test\")\n```\n\n## 4.3: Cascading Cleanup\n\nAfter removing a symbol, check if its removal creates new dead code:\n- Imports that are now unused\n- Helper functions only called by the removed symbol\n- Types only used by the removed symbol\n\nRemove cascading dead code in the same batch.\n\n## 4.4: MEDIUM Confidence Handling\n\nBefore removing MEDIUM confidence symbols, ask the user:\n\n```\nThe following MEDIUM confidence symbols appear unused but may have external consumers:\n\n1. [symbol] in [file] - [reason for medium confidence]\n\nShould I:\n1. Remove them (I confirm they are unused)\n2. Skip them (keep for now)\n3. Review each one individually\n```\n\n**Mark PHASE 4 as completed.**\n\n---\n\n# PHASE 5: FINAL VERIFICATION\n\n**Mark PHASE 5 as in_progress.**\n\n## 5.1: Full Build Check\n\n```bash\ntsc --noEmit\nbun run build\n```\n\n## 5.2: Full Test Suite\n\n```bash\nbun test\n```\n\n## 5.3: Diagnostics on Changed Files\n\n```typescript\n// Check all files that were modified\nfor (file of modifiedFiles) {\n lsp_diagnostics(file)\n}\n```\n\n## 5.4: Generate Summary\n\n```\n## Dead Code Removal Complete\n\n### Removed\n- [N] HIGH confidence symbols removed\n- [N] MEDIUM confidence symbols removed (user-approved)\n- [N] cascading cleanups (unused imports, helper functions)\n\n### Preserved\n- [N] LOW confidence symbols (manual review needed)\n- [N] MEDIUM confidence symbols (user chose to keep)\n\n### Files Modified\n- \\`path/to/file.ts\\` - removed [symbol1], [symbol2]\n- \\`path/to/file2.ts\\` - removed [symbol3]\n\n### Verification\n- Type Check: PASSED\n- Build: PASSED\n- Tests: PASSED ([X] passing, [Y] pre-existing failures)\n- Diagnostics: CLEAN (no new errors)\n\n### Lines of Code Removed: [N]\n```\n\n**Mark PHASE 5 as completed.**\n\n---\n\n# CRITICAL RULES\n\n## NEVER DO\n- Remove symbols from barrel/index files without checking all consumers\n- Remove exported symbols without checking external package consumers\n- Remove symbols referenced in configuration files, scripts, or non-TS files\n- Skip lsp_diagnostics after removal\n- Proceed with failing tests after removal\n- Remove event handlers, lifecycle hooks, or decorator-referenced symbols\n- Remove symbols used in dependency injection containers\n- Use `as any`, `@ts-ignore`, `@ts-expect-error` to suppress removal side effects\n\n## ALWAYS DO\n- Use LspFindReferences (not grep) as the primary reference detection method\n- Cross-check with grep/AST-Grep for dynamic references\n- Verify build and tests after each removal batch\n- Ask for user confirmation before removing MEDIUM confidence symbols\n- Report LOW confidence findings without auto-removing\n- Clean up cascading dead code (unused imports, orphaned helpers)\n- Keep todos updated in real-time\n\n## ABORT CONDITIONS\nIf any of these occur, STOP and consult user:\n- Build fails after removal\n- Tests fail after removal (new failures, not pre-existing)\n- More than 20 symbols flagged as dead in a single file (likely misconfiguration)\n- Removed symbol is referenced in non-TypeScript files (configs, scripts)\n\n<user-request>\n$ARGUMENTS\n</user-request>\n";
|
|
@@ -1 +1 @@
|
|
|
1
|
-
export declare const STOP_CONTINUATION_TEMPLATE = "Stop all continuation mechanisms for the current session.\n\nThis command will:\n1. Stop the
|
|
1
|
+
export declare const STOP_CONTINUATION_TEMPLATE = "Stop all continuation mechanisms for the current session.\n\nThis command will:\n1. Stop the task-continuation-enforcer from automatically continuing incomplete tasks\n2. Cancel any active Matrix Loop\n3. Clear the mission state for the current project\n\nAfter running this command:\n- The session will not auto-continue when idle\n- You can manually continue work when ready\n- The stop state is per-session and clears when the session ends\n\nUse this when you need to pause automated continuation and take manual control.";
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import type { Task } from "../task-storage/types";
|
|
2
|
+
/**
|
|
3
|
+
* Maximum parentID hops followed from a candidate to an in-scope ancestor.
|
|
4
|
+
* Mirrors `MAX_PARENT_DEPTH = 3` in `task-link.ts`: candidate → parent (1) →
|
|
5
|
+
* grandparent (2) → great-grandparent (3). A task at hop 4 or beyond is not included.
|
|
6
|
+
*/
|
|
7
|
+
export declare const DEFAULT_ANCESTRY_DEPTH = 3;
|
|
8
|
+
export interface AncestryOptions {
|
|
9
|
+
/** Directory holding the `T-*.json` store; parents are resolved inside it only. */
|
|
10
|
+
taskDir: string;
|
|
11
|
+
/** Max parentID hops. Defaults to {@link DEFAULT_ANCESTRY_DEPTH}. */
|
|
12
|
+
depth?: number;
|
|
13
|
+
}
|
|
14
|
+
/**
|
|
15
|
+
* Expand an in-scope task set with every candidate whose `parentID` chain reaches it.
|
|
16
|
+
*
|
|
17
|
+
* Returns `scoped` plus the newly admitted candidates, preserving input order. The
|
|
18
|
+
* walk is one pass over the candidates against the *original* in-scope set, so it
|
|
19
|
+
* cannot run away: adding a candidate never creates a new root that a later candidate
|
|
20
|
+
* could hang off. Two candidates chained to each other (both foreign) are therefore
|
|
21
|
+
* both excluded — correct, since neither is anchored to this session.
|
|
22
|
+
*/
|
|
23
|
+
export declare function expandByParentAncestry(scoped: Task[], candidates: Task[], opts: AncestryOptions): Task[];
|