opencode-matrixx 2.6.12 → 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/dynamic-agent-prompt-builder.d.ts +4 -4
- package/dist/agents/keymaker.d.ts +1 -1
- package/dist/agents/model-directives.d.ts +7 -0
- 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 +17 -10
- package/dist/config/schema/dcp.d.ts +15 -11
- package/dist/config/schema/experimental.d.ts +1 -1
- package/dist/config/schema/hooks.d.ts +4 -5
- package/dist/config/schema/matrixx-config.d.ts +8 -6
- package/dist/config/schema/tasks.d.ts +5 -1
- package/dist/create-hooks.d.ts +3 -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/session-state/state.d.ts +3 -0
- 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/dcp-nudge-sanitizer/constants.d.ts +2 -0
- package/dist/hooks/dcp-nudge-sanitizer/hook.d.ts +25 -0
- package/dist/hooks/dcp-nudge-sanitizer/index.d.ts +1 -0
- package/dist/hooks/index.d.ts +3 -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/nudge-loop-breaker/constants.d.ts +9 -0
- package/dist/hooks/nudge-loop-breaker/hook.d.ts +18 -0
- package/dist/hooks/nudge-loop-breaker/index.d.ts +1 -0
- package/dist/hooks/nudge-loop-breaker/session-state.d.ts +11 -0
- 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 +1834 -2138
- package/dist/matrixx.schema.json +69 -18
- package/dist/plugin/hooks/create-continuation-hooks.d.ts +2 -3
- package/dist/plugin/hooks/create-core-hooks.d.ts +2 -2
- package/dist/plugin/hooks/create-tool-guard-hooks.d.ts +2 -3
- package/dist/plugin/hooks/create-transform-hooks.d.ts +2 -0
- package/dist/plugin-handlers/task-permissions.d.ts +48 -0
- package/dist/shared/dcp-switch-profile.d.ts +12 -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/cli/setup/config-writer.test.d.ts +0 -1
- package/dist/cli/setup/deps.test.d.ts +0 -1
- package/dist/cli/setup/index.test.d.ts +0 -1
- package/dist/cli/setup/opencode-sync.test.d.ts +0 -1
- package/dist/cli/setup/prompts.test.d.ts +0 -1
- package/dist/features/background-agent/handle-index.test.d.ts +0 -1
- package/dist/features/background-agent/manager-handles.test.d.ts +0 -1
- package/dist/features/knowledge-hub/loader.test.d.ts +0 -1
- package/dist/features/knowledge-hub/resolver.test.d.ts +0 -1
- package/dist/features/mission-state/plan-storage.test.d.ts +0 -1
- package/dist/features/mission-state/reconcile.test.d.ts +0 -1
- package/dist/features/session-state/state.test.d.ts +0 -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/input-secret-guard/detector.test.d.ts +0 -1
- package/dist/hooks/input-secret-guard/hook.test.d.ts +0 -1
- package/dist/hooks/input-secret-guard/redactor.test.d.ts +0 -1
- package/dist/hooks/input-secret-guard/session-allow-cache.test.d.ts +0 -1
- package/dist/hooks/interactive-bash-session/hook.test.d.ts +0 -1
- package/dist/hooks/knowledge-hub-guard/hook.test.d.ts +0 -1
- package/dist/hooks/knowledge-hub-injector/hook.test.d.ts +0 -1
- package/dist/hooks/knowledge-hub-search-nudge/hook.test.d.ts +0 -1
- package/dist/hooks/plan-persister/task-sync.test.d.ts +0 -1
- package/dist/hooks/rtk-bash-rewriter/hook.test.d.ts +0 -1
- package/dist/hooks/session-todo-status.d.ts +0 -2
- package/dist/hooks/stop-continuation-guard/repro.test.d.ts +0 -1
- package/dist/hooks/task-continuation-enforcer/awaiting-user.test.d.ts +0 -1
- package/dist/hooks/task-continuation-enforcer/continuation-injection.test.d.ts +0 -1
- package/dist/hooks/task-continuation-enforcer/countdown.test.d.ts +0 -1
- package/dist/hooks/task-continuation-enforcer/idle-event.test.d.ts +0 -1
- package/dist/hooks/task-continuation-enforcer/staleness.test.d.ts +0 -1
- package/dist/hooks/task-continuation-enforcer/todo.test.d.ts +0 -1
- package/dist/hooks/task-continuation-enforcer/ulw-bootstrap.test.d.ts +0 -1
- 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/awaiting-user.test.d.ts +0 -1
- 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/countdown.test.d.ts +0 -1
- 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/idle-event.test.d.ts +0 -1
- 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/shared/format-bytes.test.d.ts +0 -1
- package/dist/shared/is-abort-error.test.d.ts +0 -1
- package/dist/shared/task-system-gating.test.d.ts +0 -1
- package/dist/shared/with-timeout.test.d.ts +0 -1
- package/dist/tools/delegate-task/poll-timeout-outcome.test.d.ts +0 -1
- package/dist/tools/delegate-task/prompt-builder.tdd.test.d.ts +0 -1
- package/dist/tools/delegate-task/sync-task.test.d.ts +0 -1
- package/dist/tools/delegate-task/tdd-enforcement.test.d.ts +0 -1
- package/dist/tools/delegate-task/timing.test.d.ts +0 -1
- package/dist/tools/evolution/query-actions.test.d.ts +0 -1
- package/dist/tools/evolution/tools.test.d.ts +0 -1
- package/dist/tools/github-search/result-formatter.test.d.ts +0 -1
- package/dist/tools/knowledge-hub-confirm/tools.test.d.ts +0 -1
- package/dist/tools/task/task-cleanup.test.d.ts +0 -1
package/dist/cli.js
CHANGED
|
@@ -15892,9 +15892,13 @@ var ContextModeConfigSchema = exports_external.object({
|
|
|
15892
15892
|
});
|
|
15893
15893
|
|
|
15894
15894
|
// src/config/schema/dcp.ts
|
|
15895
|
+
var dcpLimitValue = exports_external.union([exports_external.number(), exports_external.string().regex(/^\d+%$/)]);
|
|
15896
|
+
var dcpModelLimitKey = exports_external.string().regex(/^[^/]+\/[^/]+$/);
|
|
15895
15897
|
var DcpCompressOverrideSchema = exports_external.object({
|
|
15896
15898
|
maxContextLimit: exports_external.union([exports_external.number(), exports_external.string().regex(/^\d+%$/)]).optional(),
|
|
15897
15899
|
minContextLimit: exports_external.union([exports_external.number(), exports_external.string().regex(/^\d+%$/)]).optional(),
|
|
15900
|
+
modelMaxLimits: exports_external.record(dcpModelLimitKey, dcpLimitValue).optional(),
|
|
15901
|
+
modelMinLimits: exports_external.record(dcpModelLimitKey, dcpLimitValue).optional(),
|
|
15898
15902
|
nudgeFrequency: exports_external.number().int().min(1).optional(),
|
|
15899
15903
|
iterationNudgeThreshold: exports_external.number().int().min(1).optional(),
|
|
15900
15904
|
nudgeForce: exports_external.enum(["strong", "soft"]).optional(),
|
|
@@ -16094,7 +16098,7 @@ var ExperimentalConfigSchema = exports_external.object({
|
|
|
16094
16098
|
auto_resume: exports_external.boolean().optional(),
|
|
16095
16099
|
preemptive_compaction: exports_external.boolean().optional(),
|
|
16096
16100
|
truncate_all_tool_outputs: exports_external.boolean().optional(),
|
|
16097
|
-
task_system: exports_external.boolean().optional()
|
|
16101
|
+
task_system: exports_external.boolean().optional(),
|
|
16098
16102
|
plugin_load_timeout_ms: exports_external.number().min(1000).optional(),
|
|
16099
16103
|
context_warning_threshold: exports_external.number().min(0.1).max(0.95).optional(),
|
|
16100
16104
|
preemptive_compaction_threshold: exports_external.number().min(0.1).max(0.95).optional(),
|
|
@@ -16113,7 +16117,6 @@ var HeadroomConfigSchema = exports_external.object({
|
|
|
16113
16117
|
// src/config/schema/hooks.ts
|
|
16114
16118
|
var HookNameEnum = exports_external.enum([
|
|
16115
16119
|
"task-continuation-enforcer",
|
|
16116
|
-
"todo-continuation-enforcer",
|
|
16117
16120
|
"context-window-monitor",
|
|
16118
16121
|
"session-recovery",
|
|
16119
16122
|
"session-notification",
|
|
@@ -16137,7 +16140,6 @@ var HookNameEnum = exports_external.enum([
|
|
|
16137
16140
|
"matrix-loop",
|
|
16138
16141
|
"category-skill-reminder",
|
|
16139
16142
|
"compaction-context-injector",
|
|
16140
|
-
"compaction-todo-preserver",
|
|
16141
16143
|
"auto-slash-command",
|
|
16142
16144
|
"edit-error-recovery",
|
|
16143
16145
|
"delegate-task-retry",
|
|
@@ -16149,7 +16151,6 @@ var HookNameEnum = exports_external.enum([
|
|
|
16149
16151
|
"unstable-agent-babysitter",
|
|
16150
16152
|
"task-resume-info",
|
|
16151
16153
|
"stop-continuation-guard",
|
|
16152
|
-
"tasks-todowrite-disabler",
|
|
16153
16154
|
"write-existing-file-guard",
|
|
16154
16155
|
"anthropic-effort",
|
|
16155
16156
|
"hashline-read-enhancer",
|
|
@@ -16164,23 +16165,28 @@ var HookNameEnum = exports_external.enum([
|
|
|
16164
16165
|
"webfetch-redirect-guard",
|
|
16165
16166
|
"tool-pair-validator",
|
|
16166
16167
|
"quality-gate",
|
|
16167
|
-
"task-notepad",
|
|
16168
16168
|
"design-intent-preserver",
|
|
16169
16169
|
"rtk-bash-rewriter",
|
|
16170
16170
|
"evolution-watcher",
|
|
16171
16171
|
"evolution-compressor",
|
|
16172
16172
|
"evolution-hitl",
|
|
16173
16173
|
"context-mode-enforcer",
|
|
16174
|
-
"context-mode-enforcer",
|
|
16175
16174
|
"task-edit-guard",
|
|
16176
16175
|
"document-reader-guard",
|
|
16177
16176
|
"knowledge-hub-guard",
|
|
16178
16177
|
"knowledge-hub-injector",
|
|
16179
|
-
"knowledge-hub-search-nudge"
|
|
16178
|
+
"knowledge-hub-search-nudge",
|
|
16179
|
+
"dcp-nudge-sanitizer",
|
|
16180
|
+
"nudge-loop-breaker",
|
|
16181
|
+
"task-notepad-writer"
|
|
16180
16182
|
]);
|
|
16181
16183
|
var HookNameSchema = exports_external.union([
|
|
16182
16184
|
HookNameEnum,
|
|
16183
|
-
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")
|
|
16184
16190
|
]);
|
|
16185
16191
|
|
|
16186
16192
|
// src/config/schema/knowledge.ts
|
|
@@ -16273,7 +16279,7 @@ var MorpheusTasksConfigSchema = exports_external.object({
|
|
|
16273
16279
|
storage_path: exports_external.string().optional(),
|
|
16274
16280
|
task_list_id: exports_external.string().optional(),
|
|
16275
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}"),
|
|
16276
|
-
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."),
|
|
16277
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.")
|
|
16278
16284
|
});
|
|
16279
16285
|
var MorpheusConfigSchema = exports_external.object({
|
|
@@ -16405,7 +16411,8 @@ var TasksConfigSchema = exports_external.object({
|
|
|
16405
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}"),
|
|
16406
16412
|
storage_path: exports_external.string().optional(),
|
|
16407
16413
|
task_list_id: exports_external.string().optional(),
|
|
16408
|
-
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."),
|
|
16409
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."),
|
|
16410
16417
|
pollTimeoutMs: exports_external.number().min(60000).optional()
|
|
16411
16418
|
});
|
|
@@ -1,15 +1,9 @@
|
|
|
1
1
|
import { z } from "zod";
|
|
2
|
-
/**
|
|
3
|
-
* DCP (Dynamic Context Pruning) configuration.
|
|
4
|
-
*
|
|
5
|
-
* Selects between predefined DCP profile tiers
|
|
6
|
-
* (economy/balanced/performance/ultimate) via `dcp.default_profile`.
|
|
7
|
-
*
|
|
8
|
-
* DCP must be installed as a plugin: `~/.config/opencode/node_modules/@tarquinen/opencode-dcp`
|
|
9
|
-
*/
|
|
10
2
|
export declare const DcpCompressOverrideSchema: z.ZodObject<{
|
|
11
3
|
maxContextLimit: z.ZodOptional<z.ZodUnion<readonly [z.ZodNumber, z.ZodString]>>;
|
|
12
4
|
minContextLimit: z.ZodOptional<z.ZodUnion<readonly [z.ZodNumber, z.ZodString]>>;
|
|
5
|
+
modelMaxLimits: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnion<readonly [z.ZodNumber, z.ZodString]>>>;
|
|
6
|
+
modelMinLimits: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnion<readonly [z.ZodNumber, z.ZodString]>>>;
|
|
13
7
|
nudgeFrequency: z.ZodOptional<z.ZodNumber>;
|
|
14
8
|
iterationNudgeThreshold: z.ZodOptional<z.ZodNumber>;
|
|
15
9
|
nudgeForce: z.ZodOptional<z.ZodEnum<{
|
|
@@ -45,6 +39,8 @@ export declare const DcpProfileDefinitionSchema: z.ZodObject<{
|
|
|
45
39
|
compress: z.ZodOptional<z.ZodObject<{
|
|
46
40
|
maxContextLimit: z.ZodOptional<z.ZodUnion<readonly [z.ZodNumber, z.ZodString]>>;
|
|
47
41
|
minContextLimit: z.ZodOptional<z.ZodUnion<readonly [z.ZodNumber, z.ZodString]>>;
|
|
42
|
+
modelMaxLimits: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnion<readonly [z.ZodNumber, z.ZodString]>>>;
|
|
43
|
+
modelMinLimits: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnion<readonly [z.ZodNumber, z.ZodString]>>>;
|
|
48
44
|
nudgeFrequency: z.ZodOptional<z.ZodNumber>;
|
|
49
45
|
iterationNudgeThreshold: z.ZodOptional<z.ZodNumber>;
|
|
50
46
|
nudgeForce: z.ZodOptional<z.ZodEnum<{
|
|
@@ -163,9 +159,15 @@ export declare const BUILTIN_DCP_PROFILES: {
|
|
|
163
159
|
readonly compress: {
|
|
164
160
|
readonly maxContextLimit: "20%";
|
|
165
161
|
readonly minContextLimit: "10%";
|
|
166
|
-
readonly nudgeFrequency:
|
|
167
|
-
readonly nudgeForce: "
|
|
168
|
-
readonly iterationNudgeThreshold:
|
|
162
|
+
readonly nudgeFrequency: 3;
|
|
163
|
+
readonly nudgeForce: "soft";
|
|
164
|
+
readonly iterationNudgeThreshold: 6;
|
|
165
|
+
readonly modelMaxLimits: {
|
|
166
|
+
readonly "deepseek/deepseek-v4.1-flash": "95%";
|
|
167
|
+
};
|
|
168
|
+
readonly modelMinLimits: {
|
|
169
|
+
readonly "deepseek/deepseek-v4.1-flash": "90%";
|
|
170
|
+
};
|
|
169
171
|
};
|
|
170
172
|
readonly turnProtection: {
|
|
171
173
|
readonly enabled: false;
|
|
@@ -207,6 +209,8 @@ export declare const DcpConfigSchema: z.ZodObject<{
|
|
|
207
209
|
compress: z.ZodOptional<z.ZodObject<{
|
|
208
210
|
maxContextLimit: z.ZodOptional<z.ZodUnion<readonly [z.ZodNumber, z.ZodString]>>;
|
|
209
211
|
minContextLimit: z.ZodOptional<z.ZodUnion<readonly [z.ZodNumber, z.ZodString]>>;
|
|
212
|
+
modelMaxLimits: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnion<readonly [z.ZodNumber, z.ZodString]>>>;
|
|
213
|
+
modelMinLimits: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnion<readonly [z.ZodNumber, z.ZodString]>>>;
|
|
210
214
|
nudgeFrequency: z.ZodOptional<z.ZodNumber>;
|
|
211
215
|
iterationNudgeThreshold: z.ZodOptional<z.ZodNumber>;
|
|
212
216
|
nudgeForce: z.ZodOptional<z.ZodEnum<{
|
|
@@ -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";
|
|
@@ -64,5 +60,8 @@ export declare const HookNameSchema: z.ZodUnion<readonly [z.ZodEnum<{
|
|
|
64
60
|
"knowledge-hub-guard": "knowledge-hub-guard";
|
|
65
61
|
"knowledge-hub-injector": "knowledge-hub-injector";
|
|
66
62
|
"knowledge-hub-search-nudge": "knowledge-hub-search-nudge";
|
|
67
|
-
|
|
63
|
+
"dcp-nudge-sanitizer": "dcp-nudge-sanitizer";
|
|
64
|
+
"nudge-loop-breaker": "nudge-loop-breaker";
|
|
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">]>;
|
|
68
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";
|
|
@@ -137,7 +133,10 @@ export declare const MatrixxConfigSchema: z.ZodObject<{
|
|
|
137
133
|
"knowledge-hub-guard": "knowledge-hub-guard";
|
|
138
134
|
"knowledge-hub-injector": "knowledge-hub-injector";
|
|
139
135
|
"knowledge-hub-search-nudge": "knowledge-hub-search-nudge";
|
|
140
|
-
|
|
136
|
+
"dcp-nudge-sanitizer": "dcp-nudge-sanitizer";
|
|
137
|
+
"nudge-loop-breaker": "nudge-loop-breaker";
|
|
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">]>>>;
|
|
141
140
|
disabled_commands: z.ZodOptional<z.ZodArray<z.ZodEnum<{
|
|
142
141
|
"init-deep": "init-deep";
|
|
143
142
|
"matrix-loop": "matrix-loop";
|
|
@@ -1563,7 +1562,7 @@ export declare const MatrixxConfigSchema: z.ZodObject<{
|
|
|
1563
1562
|
auto_resume: z.ZodOptional<z.ZodBoolean>;
|
|
1564
1563
|
preemptive_compaction: z.ZodOptional<z.ZodBoolean>;
|
|
1565
1564
|
truncate_all_tool_outputs: z.ZodOptional<z.ZodBoolean>;
|
|
1566
|
-
task_system: z.
|
|
1565
|
+
task_system: z.ZodOptional<z.ZodBoolean>;
|
|
1567
1566
|
plugin_load_timeout_ms: z.ZodOptional<z.ZodNumber>;
|
|
1568
1567
|
context_warning_threshold: z.ZodOptional<z.ZodNumber>;
|
|
1569
1568
|
preemptive_compaction_threshold: z.ZodOptional<z.ZodNumber>;
|
|
@@ -1581,6 +1580,8 @@ export declare const MatrixxConfigSchema: z.ZodObject<{
|
|
|
1581
1580
|
compress: z.ZodOptional<z.ZodObject<{
|
|
1582
1581
|
maxContextLimit: z.ZodOptional<z.ZodUnion<readonly [z.ZodNumber, z.ZodString]>>;
|
|
1583
1582
|
minContextLimit: z.ZodOptional<z.ZodUnion<readonly [z.ZodNumber, z.ZodString]>>;
|
|
1583
|
+
modelMaxLimits: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnion<readonly [z.ZodNumber, z.ZodString]>>>;
|
|
1584
|
+
modelMinLimits: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnion<readonly [z.ZodNumber, z.ZodString]>>>;
|
|
1584
1585
|
nudgeFrequency: z.ZodOptional<z.ZodNumber>;
|
|
1585
1586
|
iterationNudgeThreshold: z.ZodOptional<z.ZodNumber>;
|
|
1586
1587
|
nudgeForce: z.ZodOptional<z.ZodEnum<{
|
|
@@ -1757,6 +1758,7 @@ export declare const MatrixxConfigSchema: z.ZodObject<{
|
|
|
1757
1758
|
storage_path: z.ZodOptional<z.ZodString>;
|
|
1758
1759
|
task_list_id: z.ZodOptional<z.ZodString>;
|
|
1759
1760
|
stale_after_hours: z.ZodOptional<z.ZodNumber>;
|
|
1761
|
+
background_stale_after_hours: z.ZodOptional<z.ZodDefault<z.ZodNumber>>;
|
|
1760
1762
|
session_scoped: z.ZodOptional<z.ZodDefault<z.ZodBoolean>>;
|
|
1761
1763
|
pollTimeoutMs: z.ZodOptional<z.ZodNumber>;
|
|
1762
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,10 +17,9 @@ 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;
|
|
22
|
+
nudgeLoopBreaker: ReturnType<typeof import("./hooks").createNudgeLoopBreakerHook> | null;
|
|
24
23
|
backgroundNotificationHook: ReturnType<typeof import("./hooks").createBackgroundNotificationHook> | null;
|
|
25
24
|
architectHook: ReturnType<typeof import("./hooks").createArchitectHook> | null;
|
|
26
25
|
planPersister: ReturnType<typeof import("./hooks").createPlanPersister> | null;
|
|
@@ -32,6 +31,7 @@ export declare function createHooks(args: {
|
|
|
32
31
|
knowledgeHubInjector: ReturnType<typeof import("./hooks").createKnowledgeHubInjectorHook> | null;
|
|
33
32
|
envContextInjector: ReturnType<typeof import("./hooks").createEnvContextInjectorHook> | null;
|
|
34
33
|
thinkingBlockValidator: ReturnType<typeof import("./hooks").createThinkingBlockValidatorHook> | null;
|
|
34
|
+
dcpNudgeSanitizer: ReturnType<typeof import("./hooks").createDcpNudgeSanitizerHook> | null;
|
|
35
35
|
toolPairValidator: ReturnType<typeof import("./hooks").createToolPairValidatorHook> | null;
|
|
36
36
|
designIntentPreserver: ReturnType<typeof import("./hooks").createDesignIntentPreserverHook> | null;
|
|
37
37
|
backgroundTaskBlocker: ReturnType<typeof import("./hooks").createBackgroundTaskBlockerHook> | null;
|
|
@@ -40,7 +40,6 @@ export declare function createHooks(args: {
|
|
|
40
40
|
directoryAgentsInjector: ReturnType<typeof import("./hooks").createDirectoryAgentsInjectorHook> | null;
|
|
41
41
|
emptyTaskResponseDetector: ReturnType<typeof import("./hooks").createEmptyTaskResponseDetectorHook> | null;
|
|
42
42
|
rulesInjector: ReturnType<typeof import("./hooks").createRulesInjectorHook> | null;
|
|
43
|
-
tasksTodowriteDisabler: ReturnType<typeof import("./hooks").createTasksTodowriteDisablerHook> | null;
|
|
44
43
|
writeExistingFileGuard: ReturnType<typeof import("./hooks").createWriteExistingFileGuardHook> | null;
|
|
45
44
|
hashlineReadEnhancer: ReturnType<typeof import("./hooks").createHashlineReadEnhancerHook> | null;
|
|
46
45
|
secretLeakGuard: ReturnType<typeof import("./hooks").createSecretLeakGuardHook> | null;
|
|
@@ -51,8 +50,8 @@ export declare function createHooks(args: {
|
|
|
51
50
|
readImageResizer: ReturnType<typeof import("./hooks").createReadImageResizerHook> | null;
|
|
52
51
|
webfetchRedirectGuard: ReturnType<typeof import("./hooks").createWebFetchRedirectGuardHook> | null;
|
|
53
52
|
qualityGate: ReturnType<typeof import("./hooks").createQualityGateHook> | null;
|
|
54
|
-
taskNotepad: ReturnType<typeof import("./hooks").createTaskNotepadHook> | null;
|
|
55
53
|
taskEditGuard: ReturnType<typeof import("./hooks").createTaskEditGuardHook> | null;
|
|
54
|
+
taskNotepadWriter: ReturnType<typeof import("./hooks").createTaskNotepadWriterHook> | null;
|
|
56
55
|
documentReaderGuard: ReturnType<typeof import("./hooks").createDocumentReaderGuardHook> | null;
|
|
57
56
|
knowledgeHubGuard: ReturnType<typeof import("./hooks").createKnowledgeHubGuardHook> | null;
|
|
58
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";
|