@cortex-agent/server 2026.6.15 → 2026.6.18

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.
Files changed (39) hide show
  1. package/defaults/config/thread-templates.json +2 -2
  2. package/defaults/hooks/task-status-check.mjs +9 -7
  3. package/defaults/plugins/cortex-stage-gate/skills/task/SKILL.md +103 -16
  4. package/defaults/plugins/cortex-system/skills/orient/SKILL.md +6 -6
  5. package/defaults/plugins/cortex-system/skills/thread/SKILL.md +29 -35
  6. package/defaults/prompts/directives/manager.md +21 -11
  7. package/dist/agent-adapter/claude/spawn-args.d.ts +5 -0
  8. package/dist/agent-adapter/claude/spawn-args.js +6 -0
  9. package/dist/agent-adapter/types.d.ts +4 -0
  10. package/dist/core/task-parser.d.ts +6 -0
  11. package/dist/core/task-parser.js +10 -0
  12. package/dist/core/types/thread-types.d.ts +29 -0
  13. package/dist/domain/agents/facade.d.ts +4 -0
  14. package/dist/domain/agents/facade.js +3 -1
  15. package/dist/domain/mcp/core-server.js +15 -9
  16. package/dist/domain/mcp/tools/task-monitor.d.ts +2 -0
  17. package/dist/domain/mcp/tools/task-monitor.js +99 -0
  18. package/dist/domain/mcp/tools/thread-ops.js +50 -85
  19. package/dist/domain/scheduling/jobs/task-dispatch.js +12 -6
  20. package/dist/domain/tasks/dispatch-utils.d.ts +5 -0
  21. package/dist/domain/tasks/dispatch-utils.js +9 -1
  22. package/dist/domain/tasks/dispatcher.js +4 -4
  23. package/dist/domain/tasks/system/task-cli.d.ts +1 -0
  24. package/dist/domain/tasks/system/task-cli.js +82 -6
  25. package/dist/domain/tasks/system/task-mutations.d.ts +6 -1
  26. package/dist/domain/tasks/system/task-mutations.js +10 -1
  27. package/dist/domain/threads/hook-runner.js +1 -0
  28. package/dist/domain/threads/prompt-builder.js +15 -9
  29. package/dist/domain/threads/runner.d.ts +5 -0
  30. package/dist/domain/threads/runner.js +44 -11
  31. package/dist/domain/threads/state-machine.d.ts +9 -12
  32. package/dist/domain/threads/state-machine.js +27 -50
  33. package/dist/hooks/task-status-check.mjs +9 -7
  34. package/dist/orchestration/routing/webhook.js +38 -1
  35. package/dist/orchestration/thread-callback.d.ts +11 -1
  36. package/dist/orchestration/thread-callback.js +66 -30
  37. package/dist/platform/adapters/feishu.d.ts +11 -0
  38. package/dist/platform/adapters/feishu.js +74 -3
  39. package/package.json +1 -1
@@ -306,7 +306,7 @@
306
306
  },
307
307
  "manager": {
308
308
  "name": "manager",
309
- "description": "Resident manager of a composite task node (DR-0014 \u00a78): decomposes into child tasks (decompose --keep-parent), suspends via [WAIT_CHILDREN], re-enters its own session to verify deliverables, rework, or escalate. persistSession is load-bearing \u2014 re-entry resumes the SAME session with full memory.",
309
+ "description": "Resident manager of a composite task node (DR-0014 \u00a78): decomposes into child tasks (decompose --keep-parent), suspends via the thread_wait tool, re-enters its own session to verify deliverables, rework, or escalate. persistSession is load-bearing \u2014 re-entry resumes the SAME session with full memory.",
310
310
  "profile": "__active__",
311
311
  "persistSession": true,
312
312
  "directive": "file:manager.md",
@@ -581,7 +581,7 @@
581
581
  },
582
582
  "manager": {
583
583
  "name": "manager",
584
- "description": "Composite-task node manager (DR-0014 \u00a78). Single resident agent: Phase A decomposes the task into children (keep-parent) and suspends on [WAIT_CHILDREN]; woken per task.completed/task.blocked events, Phase B verifies deliverables against done_when, reworks or escalates, finally completes its own task. Assign this template at task creation to any task expected to span 2+ independently verifiable units.",
584
+ "description": "Composite-task node manager (DR-0014 \u00a78). Single resident agent: Phase A decomposes the task into children (keep-parent) and suspends via the thread_wait tool; woken per task.completed/task.blocked events, Phase B verifies deliverables against done_when, reworks or escalates, finally completes its own task. Assign this template at task creation to any task expected to span 2+ independently verifiable units.",
585
585
  "agents": [
586
586
  "manager"
587
587
  ],
@@ -119,13 +119,15 @@ async function main() {
119
119
 
120
120
  if (!project || !taskId) { noop(); return; }
121
121
 
122
- // [SPLIT] decomposition proposal (DR-0014): the task is INTENTIONALLY not done — the
123
- // dispatcher decomposes it keep-parent and unclaims. Don't burn an agent turn nagging.
124
- if ((ctx.artifactContent || '').includes('[SPLIT]')) { noop(); return; }
125
-
126
- // [ABORT] worker escalation (DR-0014 §8): the dispatcher blocks the task with the abort
127
- // reason right after this hook returns — the task is intentionally not done.
128
- if (/\[ABORT(?::|\])/.test(ctx.artifactContent || '')) { noop(); return; }
122
+ // Out-of-band control intent (DR-0015): the agent signalled abort/split/wait via a tool, not
123
+ // by writing a marker into the artifact. Read the typed signal — never scan the artifact (prose
124
+ // mentioning "[ABORT]"/"[SPLIT]" must not trip this).
125
+ // - split: the task is INTENTIONALLY not done — the dispatcher decomposes it keep-parent and
126
+ // unclaims right after this hook returns. Don't burn an agent turn nagging. (The runner
127
+ // leaves pendingControl set for the dispatch path, so it is still present here.)
128
+ // - abort: the runner already blocked the task BEFORE this hook (DR-0015 problem 2) and cleared
129
+ // the control, so the blocked-by guard below covers it; this is belt-and-suspenders.
130
+ if (ctx.pendingControlAction === 'split' || ctx.pendingControlAction === 'abort') { noop(); return; }
129
131
 
130
132
  const tasksPath = path.join(PROJECTS_DIR, project, 'TASKS.yaml');
131
133
  if (!existsSync(tasksPath)) { noop(); return; }
@@ -295,19 +295,71 @@ The `gpu` field specifies that a task needs to use GPU on a particular machine.
295
295
 
296
296
  ### Task Decomposition
297
297
 
298
- #### Iron Rule 1: One-Criterion-One-Task
298
+ **The variable you optimize is decomposability, not fineness.** A good cut is the one that
299
+ falls at the *narrowest interface* between the pieces (lowest coupling), NOT the one that
300
+ produces the *most* pieces. Splitting a task into many tightly-coupled fragments — each of
301
+ which still needs the whole system in context to do its part — is worse than not splitting at
302
+ all: you pay full delegation overhead and every fragment drifts. Cut where the seam is thin;
303
+ leave coupled work whole.
299
304
 
300
- **Each independently completable/verifiable condition in the Done when must be a separate task.**
305
+ #### Iron Rule 1: Cut at the Seam
301
306
 
302
- Judgment criteria: After condition A is completed, even if condition B has not started, is the result of A already usable? If yes, it must be split.
307
+ A condition being **independently verifiable is necessary but not sufficient** to make it its
308
+ own task. The cut is valid only when, in addition:
303
309
 
304
- **Anti-pattern: Checklist-in-Task** — Do not use numbered sub-conditions (1)(2)(3)... to pack multiple independent work items into a single "Done when".
310
+ - **(a) Verifiable without naming the sibling's internals**: the child's `done-when` can be
311
+ written and checked without dictating *how* another child is implemented (no "call the
312
+ `foo()` that task X creates" at line level). If you must specify another child's
313
+ implementation to make this one verifiable, the seam is in the wrong place.
314
+ - **(b) Interface-stable**: if a sibling's internal implementation changed but its *interface*
315
+ held, this child would not need to change. If a sibling's internal change forces this child
316
+ to change, they are coupled — keep them in one task.
305
317
 
306
- **Exception 1 — Atomic verification**: Multiple sub-conditions are different verification dimensions of the same atomic operation (e.g., "script runs without errors + output file exists + metrics within reasonable range").
318
+ "One criterion = one task" still holds **as a corollary** when the criteria are genuinely
319
+ decoupled (the usual case for independent experiments / parallel artifacts). It does NOT hold
320
+ when criteria share mutable state or a single evolving abstraction.
307
321
 
308
- **Exception 2 — Article writing**: Long-form writing tasks such as papers are not split by section; execute as a single task to ensure cross-section coherence.
322
+ **Anti-pattern: Checklist-in-Task** — Do not use numbered sub-conditions (1)(2)(3)... to pack
323
+ multiple *independent* work items into one "Done when".
309
324
 
310
- **Example**:
325
+ **Exception 1 — Atomic verification**: Multiple sub-conditions are different verification
326
+ dimensions of the same atomic operation (e.g., "script runs without errors + output file
327
+ exists + metrics within reasonable range").
328
+
329
+ **Exception 2 — Article writing**: Long-form writing such as papers is not split by section;
330
+ execute as a single task to ensure cross-section coherence.
331
+
332
+ #### Decomposition self-audit (run per child BEFORE committing the split)
333
+
334
+ For each proposed child, answer all four. **Any "no" → re-cut, merge, or refuse to split.**
335
+ Do not treat the split as final until every child passes.
336
+
337
+ 1. **Interface stated in 1–2 lines?** Can you say what this child consumes and what it
338
+ produces in one or two lines? Can't state it crisply → the interface is fat → bad cut.
339
+ 2. **`done-when` verifiable without naming implementation?** If you have to name specific
340
+ functions/lines of another child to verify this one → either it is actually a leaf (just do
341
+ it inline, don't spawn) or the cut is wrong.
342
+ 3. **Survives a sibling refactor?** If a sibling's interface holds but its internals change,
343
+ does this child stay unaffected? If not → coupled → merge them.
344
+ 4. **Distinct context from the parent?** Does this child read a meaningfully *smaller /
345
+ different* slice of context than the parent? If it needs the same broad context → the cut
346
+ bought nothing.
347
+
348
+ #### When NOT to decompose
349
+
350
+ Forcing a split on a non-decomposable problem produces drift, not progress. If no thin seam
351
+ exists (the self-audit keeps failing because everything depends on everything — a tangled
352
+ reconcile loop, a single evolving abstraction, shared mutable state):
353
+
354
+ - **Do the coupled core whole**, in one strong-model task. Coupling that cannot be cut is a
355
+ signal to keep the work together, not to fragment it.
356
+ - **Or create a "refactor to expose seams" task first**, then decompose the now-modular result.
357
+ "Make it decomposable" is itself a legitimate task.
358
+
359
+ Refusing to split, with a one-line reason, is a valid and often correct outcome.
360
+
361
+ **Example A — clean seam (parallel, DO split)**: independent experiments share no mutable
362
+ state; each passes the self-audit.
311
363
 
312
364
  ```yaml
313
365
  # ❌ 3 independent experiments + analysis packed into 1 task
@@ -338,6 +390,37 @@ Judgment criteria: After condition A is completed, even if condition B has not s
338
390
  done-when: "Three sets of experiment results compared and analyzed, conclusions recorded in experiments/EXP-NNN.md"
339
391
  ```
340
392
 
393
+ **Example B — coupled code (DON'T fine-split)**: "fix the reconcile loop so state X, Y, Z
394
+ converge" reads like three criteria, but X/Y/Z are updated through one shared state machine —
395
+ changing the convergence logic for X forces Y and Z to change too (self-audit #3 fails).
396
+
397
+ ```yaml
398
+ # ❌ Fine-split by symptom — each child needs the whole state machine in context, and they
399
+ # stomp on each other. Three drifting fragments, full delegation overhead, no real seam.
400
+ - id: y001
401
+ text: "Make state X converge"
402
+ done-when: "X reaches steady state"
403
+ - id: y002
404
+ text: "Make state Y converge"
405
+ done-when: "Y reaches steady state"
406
+ - id: y003
407
+ text: "Make state Z converge"
408
+ done-when: "Z reaches steady state"
409
+
410
+ # ✅ Keep the coupled core whole (one strong-model task)...
411
+ - id: y010
412
+ text: "Rework reconcile loop so X/Y/Z converge to a stable state"
413
+ plan: context/projects/foo/decisions/DR-00NN.md
414
+ done-when: "Reconcile converges X, Y, Z together under the loop's tests; no oscillation"
415
+
416
+ # ✅ ...OR, if the loop is too tangled to reason about, expose seams FIRST, then decompose
417
+ - id: y020
418
+ text: "Refactor reconcile loop to isolate X/Y/Z update paths behind a clear interface"
419
+ plan: context/projects/foo/decisions/DR-00NN.md
420
+ done-when: "Each state's update path is a separately-testable function with a stated contract"
421
+ # (a follow-up task, depends-on: [y020], may then split convergence work along the new seams)
422
+ ```
423
+
341
424
  #### Iron Rule 2: Explicit Dependency Declaration
342
425
 
343
426
  If decomposed tasks have execution order requirements, they **must use `depends-on` or `blocked-by` to explicitly declare** them. Do not rely on implicit list order.
@@ -362,14 +445,18 @@ If decomposed tasks have execution order requirements, they **must use `depends-
362
445
  done-when: "Eval metrics recorded in experiments/EXP-NNN.md"
363
446
  ```
364
447
 
365
- #### Decomposition Trigger Conditions
448
+ #### Decomposition candidate signals (NOT auto-split triggers)
449
+
450
+ These are hints that a task *might* be decomposable — they tell you to **run the self-audit**,
451
+ not to split on sight. A task touching many files or steps may still be one coupled unit; file
452
+ count is never sufficient justification to cut. Split only if the self-audit passes.
366
453
 
367
- - Done when contains multiple independently completable conditions (Iron Rule 1, highest priority)
368
- - Decomposed subtasks have sequential dependencies but are not declared (Iron Rule 2)
369
- - Has 2+ independent steps
370
- - Involves 3+ files
454
+ - Done-when contains multiple **decoupled** completable conditions (Iron Rule 1)
455
+ - Subtasks have sequential dependencies that are not yet declared (Iron Rule 2)
456
+ - 2+ steps that pass the interface-stable test (each survives the others' refactor)
457
+ - 3+ files **with a thin seam between them** (not 3+ files that all share one abstraction)
371
458
  - Mixes blocked and unblocked work
372
- - Mixes mechanical work and judgment-based work
459
+ - Mixes mechanical work and judgment-based work *and* the two have a clean handoff
373
460
 
374
461
  #### Composite Tasks: Assign the `manager` Template (DR-0014 §8)
375
462
 
@@ -380,13 +467,13 @@ investigation — do not force a premature decomposition. Instead create ONE tas
380
467
 
381
468
  - A manager thread (strong model, persistent session) is dispatched for it: it orients,
382
469
  decomposes into child tasks (`decompose --keep-parent`, children carry `parent`), suspends
383
- on `[WAIT_CHILDREN]`, and is woken to verify each child's deliverable against its done_when
470
+ via the `thread_wait` tool, and is woken to verify each child's deliverable against its done_when
384
471
  before completing the parent. Acceptance is part of the node, not an afterthought.
385
472
  - Rule of thumb: expected to span 2+ independently verifiable units, or the decomposition
386
473
  itself needs judgment → `manager`. A single well-scoped unit → a worker template
387
474
  (coder-review / execute-review / ...).
388
- - Worker escalation: a worker that discovers its task is mis-scoped writes
389
- `[ABORT: too-big — <diagnosis>]`; the task gets blocked with the diagnosis and the owning
475
+ - Worker escalation: a worker that discovers its task is mis-scoped calls the `thread_abort`
476
+ tool (kind `too-big`, with a diagnosis); the task gets blocked with the diagnosis and the owning
390
477
  manager (or a human) re-plans. Workers never decompose tasks themselves.
391
478
 
392
479
  ### Stage Boundary Constraints
@@ -54,7 +54,7 @@ Read the following in parallel:
54
54
  ### Task supply and decomposition
55
55
 
56
56
  While scanning TASKS.md files, improve task quality:
57
- - Decompose tasks with >2 independent steps into subtasks
57
+ - **Flag** tasks with >2 steps as decomposition *candidates* — do NOT auto-split. Step/file count is only a hint; apply the /task decomposition self-audit (cut at the thin seam, not the finest grain) before splitting. Many-step tasks that share one abstraction are coupled and should stay whole. When unsure, leave a candidate note rather than fragmenting.
58
58
  - Remove stale `[blocked-by]` tags where the referenced condition is resolved
59
59
  - If `ISSUES.md` shows recurring or unresolved workflow friction with no corresponding open task, decompose it into one or more concrete follow-up tasks in the same project's `TASKS.md`
60
60
 
@@ -217,11 +217,11 @@ Extract all unblocked tasks from TASKS.md files. For each task, assess:
217
217
  - If no new preconditions → prefer an alternative task
218
218
  - If no alternatives → recommend but note the repetition risk
219
219
 
220
- **Decomposition scan:** While scanning tasks, check for decomposition opportunities:
221
- 1. Tasks with >2 independent steps → split into subtasks
222
- 2. Tasks touching >3 files → split
223
- 3. Tasks mixing mechanical and judgment work → split
224
- Report any decomposition updates made.
220
+ **Decomposition scan:** While scanning tasks, surface decomposition *candidates* — these signals say "run the /task self-audit", NOT "split now":
221
+ 1. Tasks with >2 steps → candidate (split only if each step survives the others' refactor)
222
+ 2. Tasks touching >3 files → candidate (3+ files sharing one abstraction are coupled — keep whole)
223
+ 3. Tasks mixing mechanical and judgment work with a clean handoff → candidate
224
+ Cut only at thin seams (low coupling), never on count alone. Report candidates flagged and any splits actually made (with the seam justification).
225
225
 
226
226
  Do NOT recommend tasks from:
227
227
  - Tasks with `[blocked-by]` tags with unresolved blockers
@@ -59,63 +59,57 @@ Slack message / Scheduler / Task Dispatch
59
59
  | `completed` | All steps done | Yes |
60
60
  | `failed` | Unrecoverable error | Yes |
61
61
  | `cancelled` | User cancelled via `!thread cancel` | Yes |
62
- | `aborted` | Agent self-aborted via `[ABORT]` marker in artifact | Yes |
62
+ | `aborted` | Agent self-aborted via the `thread_abort` tool | Yes |
63
63
 
64
64
  ---
65
65
 
66
- ## Abort Mechanism
66
+ ## Control Plane (abort / split / wait) — DR-0015
67
67
 
68
- When an agent determines its task cannot be completed or is blocked by an irrecoverable condition, it can terminate the thread early by writing an abort marker to the artifact file.
68
+ Thread control is **out-of-band**: an agent signals its own thread by calling explicit MCP tools, NOT by writing markers into the artifact. The artifact is plain prose — text that merely mentions `[ABORT]` / `[SPLIT]` / `[WAIT_CHILDREN]` (e.g. "No [ABORT]", or a plan that says "if X then abort") triggers **nothing**. This eliminated the false-positive class behind the 2026-06-13 double-abort incident (DR-0015 problem 1).
69
69
 
70
- ### How Agents Know About Abort
70
+ ### The three control tools (self-control of the caller's own thread)
71
71
 
72
- The abort capability is **auto-injected** by the thread system — you do **not** need to add anything to an agent's directive. `thread-manager.buildStepPrompt` prepends a short `THREAD_PROTOCOL_PREAMBLE` block (defined in `agent-server/src/thread-manager.ts`) to every step prompt of any thread that owns a workspace artifact. The preamble is skipped for auto-record / default / direct paths (no artifact to write to) and skipped on `--resume` of a persistent session (already delivered on first trigger).
72
+ All three target `CORTEX_THREAD_ID` (the thread you are running inside) — you never pass a thread id. Calling outside a thread is an error. After calling, end your step; the runner consumes the signal at the next step boundary.
73
73
 
74
- Practical consequence: adding a new artifact-writing agent to `thread-templates.json` automatically gets the abort capability without editing directive / promptTemplate / systemPrompt.
74
+ - `thread_abort({ kind, diagnosis })` — terminate the thread early (terminal state `aborted`, distinct from `failed`). `kind ∈ {too-big, mis-scoped, blocked-external}`; `diagnosis` is required and becomes `thread.abortReason` (and, for a dispatch task, the task block reason). `too-big` / `mis-scoped` escalate to a re-planning manager; `blocked-external` escalates to a human.
75
+ - `thread_split({ subtasks })` — propose a decomposition of a dispatch task instead of doing it: the task is decomposed keep-parent (your task becomes the join node), unclaimed, and the children flow through the dispatch queue. `subtasks` is a typed array (decomposeTask shape).
76
+ - `thread_wait({ on_tasks?, on_threads? })` — suspend the thread until its awaited children finish; you are re-entered with their results once ALL are terminal.
75
77
 
76
- ### Marker Format
78
+ ### How Agents Know About the Control Plane
77
79
 
78
- - `[ABORT]` — terminate with no reason
79
- - `[ABORT: <reason>]` — terminate with a free-text reason (trimmed, stored in `thread.abortReason`)
80
+ The protocol is **auto-injected** by the thread system — you do **not** need to add anything to an agent's directive. `buildStepPrompt` prepends a short `THREAD_PROTOCOL_PREAMBLE` block (defined in `agent-server/src/domain/threads/prompt-builder.ts`) to every step prompt of any thread that owns a workspace artifact. The preamble is skipped for auto-record / default / direct paths (no artifact) and on `--resume` of a persistent session (already delivered). Adding a new artifact-writing agent to `thread-templates.json` automatically gets the control tools without editing its directive / promptTemplate / systemPrompt.
80
81
 
81
- The marker is matched with regex `/\[ABORT(?::\s*([^\]\n]*))?\]/`. It may appear anywhere in the artifact, but placement at the end is recommended for clarity.
82
+ ### When to Abort
82
83
 
83
- ### When to Use
84
+ Call `thread_abort` when:
84
85
 
85
- An agent should write `[ABORT: <reason>]` when:
86
+ - **Upstream is missing or malformed** — required inputs are absent or corrupt and cannot be produced by retrying.
87
+ - **Hardware / external resource unavailable** (`kind: blocked-external`) — target machine offline, GPU exhausted, external API permanently unreachable.
88
+ - **Specification unresolvable** (`kind: mis-scoped`) — the requirements contain a contradiction that cannot be decided autonomously.
89
+ - **Task is far bigger than described** (`kind: too-big`) — multiple independent units crammed together (prefer `thread_split` if you can already name the children).
86
90
 
87
- - **Upstream is missing or malformed** — required inputs (previous agent's artifact section, referenced files, dependencies) are absent or corrupt and cannot be produced by retrying.
88
- - **Hardware / external resource unavailable** — e.g., target machine offline, GPU exhausted, external API permanently unreachable.
89
- - **Specification unresolvable** — the user/task requirements contain a contradiction that cannot be decided autonomously.
90
- - **Repeated failure without signal of progress** — the agent is stuck in a loop that more retries will not fix.
91
-
92
- Do **not** abort for:
93
-
94
- - Normal retry situations (use the `[REVISED]` convention and let the reviewer loop handle it).
95
- - Minor warnings that do not block the task.
96
- - Disagreements with the plan that can be recorded as feedback in the artifact.
91
+ Do **not** abort for: normal retry situations (use the `[REVISED]` convergence convention and let the reviewer loop handle it), minor warnings, or disagreements with the plan that can be recorded as feedback in the artifact.
97
92
 
98
93
  ### Execution Semantics
99
94
 
100
- When the thread-runner detects the marker after a step completes:
95
+ When the runner reads `metadata.pendingControl` after a step completes:
101
96
 
102
- 1. Thread status → `aborted`; `abortReason` is recorded.
103
- 2. No further steps execute (transitions are skipped).
104
- 3. `onEnd` hook still fires — `/compound-simple`, git commit, and other cleanup work normally.
105
- 4. `finalizeThread` reads the artifact as the final output and flushes to Slack.
97
+ 1. `abort` → thread status `aborted`, `abortReason` recorded; for a dispatch thread the owning task is blocked BEFORE the `onEnd` hook runs (DR-0015 problem 2). No further steps. `onEnd` still fires; `finalizeThread` flushes the artifact.
98
+ 2. `split` → the runner breaks the loop leaving the signal in place; the dispatch path consumes `pendingControl.subtasks` and decomposes keep-parent.
99
+ 3. `wait` → if live children remain the thread enters `waiting`; otherwise it continues.
100
+
101
+ The signal is cleared after consumption so an intent fires exactly once; the webhook rejects a second concurrent control on the same thread.
106
102
 
107
103
  ### Comparison with Other Terminators
108
104
 
109
- | Mechanism | Who writes it | Effect |
110
- |-----------|---------------|--------|
111
- | `[APPROVED]` / `[IMPL-APPROVED]` | Reviewer agent | Convergence marker — reviewer approves, transition to next agent |
112
- | `[REVISED]` | Doer agent (after retry) | Signals retry complete; `output_not_contains` transition terminates loop |
113
- | `[ABORT[: reason]]` | Any agent | Global abort — thread enters `aborted` terminal state, overrides all transitions |
105
+ | Mechanism | Who triggers it | Effect |
106
+ |-----------|-----------------|--------|
107
+ | `[APPROVED]` / `[IMPL-APPROVED]` | Reviewer agent (artifact text) | Convergence marker — reviewer approves, transition to next agent |
108
+ | `[REVISED]` | Doer agent (artifact text, after retry) | Signals retry complete; `output_not_contains` transition terminates loop |
109
+ | `thread_abort` tool | Any agent | Global abort — thread enters `aborted` terminal state, overrides all transitions |
114
110
  | `!thread cancel` | User (Slack command) | Thread enters `cancelled` terminal state |
115
111
 
116
- ### Quoting Caveat
117
-
118
- If an agent needs to quote or reference the literal string `[ABORT]` (e.g., reviewer explaining the mechanism), it should wrap it in backticks (`` `[ABORT]` ``) or escape the brackets. The marker regex matches unescaped bracketed text anywhere in the artifact, so unquoted references can accidentally trigger abort.
112
+ (`[APPROVED]` / `[REVISED]` remain in-band transition markers matched against agent output — they are evaluated by template `transitions`, a separate mechanism from the control plane.)
119
113
 
120
114
  ---
121
115
 
@@ -17,10 +17,13 @@ run `cortex-task tree --task-id <your Task ID>` (and `cortex-task show`) to see
17
17
  ## Phase A — Decompose (no children exist yet)
18
18
 
19
19
  1. **Orient**: read the task's plan file, the project's `STATUS.md` / `mission.md` / `roadmap.md`, and any context the dispatch prompt names. Understand what "done" means for YOUR task (its done_when is the contract you'll be graded on).
20
- 2. **Judge size first**: if the task is actually leaf-sized (a single independently verifiable unit), just do it yourself and complete it — do not decompose for ceremony.
21
- 3. **Decompose by the Iron Rules** (One-Criterion-One-Task; explicit dependencies — see /task skill):
20
+ 2. **Judge decomposability, not just size**:
21
+ - If the task is leaf-sized (a single independently verifiable unit), just do it yourself and complete it — do not decompose for ceremony.
22
+ - If the task is large but **coupled** — no thin seam exists; the pieces share mutable state or one evolving abstraction so each piece would need the whole in context — do NOT force a fake split. Either do the coupled core yourself in this session (you are a strong model), or create ONE `refactor to expose seams` child first and decompose along the new seams after it lands. Forcing a split on a non-decomposable problem multiplies cost and produces drift. Refusing to split, with a one-line reason in your notes, is a valid outcome.
23
+ 3. **Map the seams BEFORE cutting** (do not skip — decomposition quality is bounded by your understanding of the *real* interfaces, which comes from reading code, not the plan doc): read the actual modules/files/interfaces your task touches and write a short **seam map** (what the natural boundaries are, what crosses each boundary). Every cut you propose must be justifiable against this map. Put the seam map in your `manager-notes` file.
24
+ 4. **Decompose by the Iron Rules** (Cut-at-the-Seam: interface-stable, verifiable without naming a sibling's internals; explicit dependencies — see /task skill):
22
25
  - Each child = one independently completable AND verifiable unit, verb-first text, concrete done_when.
23
- - Order siblings with `key` + `depends-on`. Pick each child's `template` deliberately (worker templates for execution; another `manager` for a composite child — that nests the tree).
26
+ - Order siblings with `key` + `depends-on`. Pick each child's `template` deliberately by its **residual reasoning** (how much genuine judgment is left after your decomposition), not by reflex: a child whose work is well-specified and mechanical can take a cheaper/faster worker template; a child that still carries real design judgment needs a stronger one. Do not default every leaf to the cheapest tier. Use another `manager` for a composite child — that nests the tree.
24
27
  - Create them in ONE call (exact recipe — write the JSON to a temp file first):
25
28
 
26
29
  ```bash
@@ -35,12 +38,19 @@ run `cortex-task tree --task-id <your Task ID>` (and `cortex-task show`) to see
35
38
 
36
39
  `--keep-parent` makes children hang under you (`parent`) and adds them to your task's `depends_on` — that is your disaster-recovery join: if this thread is ever lost, your task re-unlocks after all children finish and a fresh manager takes over.
37
40
  Verify with `cortex-task tree --task-id <your Task ID>` before suspending. If decompose errors, fix the JSON and retry — do NOT fall back to ad-hoc task creation that leaves children unlinked to you.
38
- 4. **Write your reasoning down** (MANDATORY — fallback memory for a fresh manager if this session is ever lost): why this decomposition, what each child must deliver, your per-child acceptance checklist. Write it BOTH to your artifact AND to `context/projects/<project>/manager-notes-<your Task ID>.md` — the project file survives thread-workspace cleanup; the artifact does not.
39
- 5. End your step with the marker `[WAIT_CHILDREN]` on its own line.
41
+ 5. **Self-audit each child BEFORE committing the split** (this is the quality gate — do it for every child, record results in your notes). Any "no" → re-cut, merge, or refuse:
42
+ - **Interface in 1–2 lines?** Can you state what the child consumes and produces crisply? Can't → fat interface → bad cut.
43
+ - **`done-when` verifiable without naming a sibling's internals?** If you must name another child's functions/lines, it's a leaf (do it inline) or the seam is wrong.
44
+ - **Survives a sibling refactor?** Sibling's interface holds but internals change → this child unaffected? If not → coupled → merge.
45
+ - **Distinct context from you?** Child reads a smaller/different slice than you? If it needs your whole context, the cut bought nothing.
46
+
47
+ If the audit keeps failing across re-cuts, the task is not decomposable here — fall back to the coupled-core / refactor-first options in step 2.
48
+ 6. **Write your reasoning down** (MANDATORY — fallback memory for a fresh manager if this session is ever lost): the seam map, why this decomposition, what each child must deliver, your per-child acceptance checklist, and the self-audit results. Write it BOTH to your artifact AND to `context/projects/<project>/manager-notes-<your Task ID>.md` — the project file survives thread-workspace cleanup; the artifact does not.
49
+ 7. Call the `thread_wait` tool, then end your step.
40
50
 
41
51
  **Queue semantics — read carefully (this is where managers go wrong):**
42
52
  - Your children are dispatched by the task queue ONLY AFTER your step ends and you suspend. You will NEVER see them start, run, or finish during your own step. Children sitting `open`/unclaimed while you are still running is the EXPECTED state, not a failure.
43
- - NEVER block, complete, or unclaim your own task in Phase A, and never conclude "the dispatcher isn't working" from inside your own step. Emit `[WAIT_CHILDREN]` and end — the system does the rest.
53
+ - NEVER block, complete, or unclaim your own task in Phase A, and never conclude "the dispatcher isn't working" from inside your own step. Call `thread_wait` and end — the system does the rest.
44
54
  - Do not poll or wait in-step. Suspension is free; polling burns budget.
45
55
 
46
56
  ## Phase B — Verify & Correct (woken with child results)
@@ -50,18 +60,18 @@ Child results arrive as injected messages; ALWAYS cross-check against `cortex-ta
50
60
  For each finished child, **acceptance before trust**:
51
61
  1. Read the actual deliverable (code, files, experiment records) and check it against the child's done_when. Run tests where code is involved. Never accept a completion note as evidence.
52
62
  2. **Pass** → distill the key conclusions into your artifact; move on.
53
- 3. **Fail** → write the expected/actual gap and your hypothesis into the artifact, then either `cortex-task uncomplete` + edit the child with a sharper contract, or add a revision child via the same `decompose --keep-parent` call. End with `[WAIT_CHILDREN]` again.
63
+ 3. **Fail** → write the expected/actual gap and your hypothesis into the artifact, then either `cortex-task uncomplete` + edit the child with a sharper contract, or add a revision child via the same `decompose --keep-parent` call. Call `thread_wait` again.
54
64
  4. **Blocked child** (escalation from a worker — e.g. `worker-abort: too-big`): this means YOUR decomposition needs revising. Diagnose, then `cortex-task unblock` + edit, or rebuild the unit as new children. Do not just retry the same contract.
55
- 5. **Direction is wrong** (the decomposition premise no longer holds, or the problem exceeds your node's authority): append `[ABORT: <one-line diagnosis>]` to the artifact — your own parent manager (or a human) re-plans with your diagnosis.
65
+ 5. **Direction is wrong** (the decomposition premise no longer holds, or the problem exceeds your node's authority): call the `thread_abort` tool with a one-line diagnosis — your own parent manager (or a human) re-plans with your diagnosis.
56
66
 
57
67
  When ALL children are verified:
58
68
  6. Integrate: check the combined result against YOUR task's original done_when (the children passing individually is not enough).
59
69
  7. Update the project's `STATUS.md`; record durable findings in the project knowledge files.
60
70
  8. `cortex-task complete --project <project> --task-id <your Task ID> --note "<what was delivered + verification evidence>"`.
61
- 9. End normally — WITHOUT `[WAIT_CHILDREN]`.
71
+ 9. End normally — WITHOUT calling `thread_wait`.
62
72
 
63
73
  # Tools & Limits
64
74
 
65
- - `thread_start` remains available for quick sub-calls that don't deserve a task (an independent verifier pass on a child's deliverable, a short research probe before deciding a split). Minutes-scale only; tree guards (width/depth/budget) apply.
66
- - Stay within your node: don't touch sibling tasks or re-plan above your level — that's what `[ABORT: <diagnosis>]` is for.
75
+ - For a quick sub-call that doesn't merit a full decomposition (an independent verifier pass on a child's deliverable, a short research probe before deciding a split), create a single child with `cortex-task spawn --text "..." --template <name>` (it hangs under you and joins via `depends_on`, like decompose) and then call `thread_wait`. It flows through the dispatch queue like any child — there is no in-process thread spawn (`thread_start` was removed; tasks are the only delegation primitive).
76
+ - Stay within your node: don't touch sibling tasks or re-plan above your level — that's what the `thread_abort` tool (with a diagnosis) is for.
67
77
  - Rework discipline: at most 2 revision rounds per child; if a unit fails a third time, escalate with your accumulated diagnosis instead of iterating.
@@ -45,5 +45,10 @@ export interface CortexAgentContext {
45
45
  /** Recursion depth of the owning thread, surfaced as CORTEX_THREAD_DEPTH so the thread_start
46
46
  * MCP tool can forward it and the daemon-side depth guard can cap nested thread spawning. */
47
47
  threadDepth?: number | null;
48
+ /** Owning dispatch task id/project (when the agent runs inside a task-dispatched thread),
49
+ * surfaced as CORTEX_TASK_ID / CORTEX_TASK_PROJECT so `cortex-task spawn` can infer the
50
+ * current task as the parent of a child task without the agent re-declaring it. */
51
+ taskId?: string | null;
52
+ taskProject?: string | null;
48
53
  }
49
54
  export declare function buildClaudeEnv(channel: string, sessionId: string, callbackSource?: string | null, scheduleTaskId?: string | null, anthropicBaseUrl?: string, extraEnv?: Record<string, string>, context?: CortexAgentContext): NodeJS.ProcessEnv;
@@ -105,6 +105,8 @@ export function buildClaudeEnv(channel, sessionId, callbackSource, scheduleTaskI
105
105
  delete env.CORTEX_PROJECT;
106
106
  delete env.CORTEX_SESSION_NAME;
107
107
  delete env.CORTEX_THREAD_DEPTH;
108
+ delete env.CORTEX_TASK_ID;
109
+ delete env.CORTEX_TASK_PROJECT;
108
110
  if (context?.threadId)
109
111
  env.CORTEX_THREAD_ID = context.threadId;
110
112
  if (context?.threadDepth != null)
@@ -117,6 +119,10 @@ export function buildClaudeEnv(channel, sessionId, callbackSource, scheduleTaskI
117
119
  env.CORTEX_SESSION_NAME = context.sessionName;
118
120
  if (context?.executionId)
119
121
  env.CORTEX_EXECUTION_ID = context.executionId;
122
+ if (context?.taskId)
123
+ env.CORTEX_TASK_ID = context.taskId;
124
+ if (context?.taskProject)
125
+ env.CORTEX_TASK_PROJECT = context.taskProject;
120
126
  if (extraEnv) {
121
127
  for (const [k, v] of Object.entries(extraEnv))
122
128
  env[k] = v;
@@ -79,6 +79,10 @@ export interface AgentSpawnConfig {
79
79
  executionId?: string | null;
80
80
  /** When true, load only core MCP server (remote_* tools). Used by template thread sessions. */
81
81
  useCoreMcp?: boolean;
82
+ threadDepth?: number | null;
83
+ /** Owning dispatch task id/project, surfaced as CORTEX_TASK_ID / CORTEX_TASK_PROJECT. */
84
+ taskId?: string | null;
85
+ taskProject?: string | null;
82
86
  };
83
87
  }
84
88
  export interface AgentProcess {
@@ -24,6 +24,12 @@ export interface Task {
24
24
  completed_at: string | null;
25
25
  completed_note: string | null;
26
26
  pending_at: string | null;
27
+ /** Provenance for session→task wake (Problem 1). Captured from CORTEX_* / channel env when a
28
+ * task is created from within a running session or agent. On task.completed, if origin_channel
29
+ * is set (and no thread is waiting on this task), the originating session is woken. */
30
+ origin_session_id: string | null;
31
+ origin_channel: string | null;
32
+ origin_thread_id: string | null;
27
33
  }
28
34
  export interface LockState {
29
35
  owner: string;
@@ -17,6 +17,9 @@ const YAML_TO_TS = {
17
17
  'completed-at': 'completed_at',
18
18
  'completed-note': 'completed_note',
19
19
  'pending-at': 'pending_at',
20
+ 'origin-session-id': 'origin_session_id',
21
+ 'origin-channel': 'origin_channel',
22
+ 'origin-thread-id': 'origin_thread_id',
20
23
  };
21
24
  const TS_TO_YAML = Object.fromEntries(Object.entries(YAML_TO_TS).map(([k, v]) => [v, k]));
22
25
  function yamlKeyToTs(key) {
@@ -47,6 +50,9 @@ const TASK_DEFAULTS = {
47
50
  completed_at: null,
48
51
  completed_note: null,
49
52
  pending_at: null,
53
+ origin_session_id: null,
54
+ origin_channel: null,
55
+ origin_thread_id: null,
50
56
  };
51
57
  // ── Parsing ──
52
58
  function rawToTask(raw, project) {
@@ -78,6 +84,9 @@ function rawToTask(raw, project) {
78
84
  completed_at: mapped.completed_at != null ? String(mapped.completed_at) : null,
79
85
  completed_note: mapped.completed_note != null ? String(mapped.completed_note) : null,
80
86
  pending_at: mapped.pending_at != null ? String(mapped.pending_at) : null,
87
+ origin_session_id: mapped.origin_session_id != null ? String(mapped.origin_session_id) : null,
88
+ origin_channel: mapped.origin_channel != null ? String(mapped.origin_channel) : null,
89
+ origin_thread_id: mapped.origin_thread_id != null ? String(mapped.origin_thread_id) : null,
81
90
  };
82
91
  }
83
92
  function parseTasksFile(content, project) {
@@ -126,6 +135,7 @@ const REQUIRED_KEYS = ['id', 'text', 'why', 'done_when', 'priority', 'status', '
126
135
  const OPTIONAL_KEY_ORDER = [
127
136
  'parent', 'depends_on', 'gpu', 'gpu_count', 'blocked_by', 'claimed_by', 'claimed_at',
128
137
  'paused', 'approval_needed', 'approved_at', 'not_before', 'pending_at', 'completed_at', 'completed_note',
138
+ 'origin_session_id', 'origin_channel', 'origin_thread_id',
129
139
  ];
130
140
  function isDefault(key, value) {
131
141
  const def = TASK_DEFAULTS[key];
@@ -117,6 +117,10 @@ export interface HookContext {
117
117
  artifactContent: string;
118
118
  userMessage: string;
119
119
  totalCostUsd: number;
120
+ /** Out-of-band control intent on this thread (DR-0015): 'abort' | 'split' | 'wait' | null.
121
+ * Hooks (e.g. task-status-check) use this — NOT artifact scanning — to tell an intentional
122
+ * non-completion (abort/split) from a stuck task. */
123
+ pendingControlAction?: 'abort' | 'split' | 'wait' | null;
120
124
  }
121
125
  /** Lifecycle hooks for thread templates */
122
126
  export interface ThreadHooks {
@@ -257,6 +261,21 @@ export interface ThreadMetadata {
257
261
  /** Live status message persisted at suspension so the post-resume settle can refresh it
258
262
  * (otherwise it reads "suspended — waiting on children" forever — 2026-06-11 finding). */
259
263
  statusMsgRef?: MessageRef | null;
264
+ /** Out-of-band control signal written by the agent's own thread_abort / thread_split /
265
+ * thread_wait MCP tool (DR-0015 problem 1). The runner reads this at the step boundary and
266
+ * CLEARS it after consuming, so a control intent fires exactly once. Replaces the old in-band
267
+ * artifact string markers ([ABORT]/[SPLIT]/[WAIT_CHILDREN]) — agent prose that merely mentions
268
+ * those tokens can no longer trigger a control action. Set only via the webhook `control`
269
+ * action, which rejects a second concurrent control on the same thread. */
270
+ pendingControl?: {
271
+ action: 'abort' | 'split' | 'wait';
272
+ kind?: string | null;
273
+ diagnosis?: string | null;
274
+ subtasks?: any[] | null;
275
+ onTasks?: string[] | null;
276
+ onThreads?: string[] | null;
277
+ requestedAtStep?: number;
278
+ } | null;
260
279
  }
261
280
  export interface StepResult {
262
281
  done: boolean;
@@ -297,6 +316,16 @@ export interface RunThreadOptions {
297
316
  multi?: boolean;
298
317
  }>;
299
318
  }) => void) | null;
319
+ /** Invoked when the thread terminates via agent abort, BEFORE onEnd hooks run, so the
320
+ * dispatch path can block the owning task in time (DR-0015 problem 2: otherwise the onEnd
321
+ * task-status-check sees a still-claimed task and "recovers" it by unclaiming, which lets the
322
+ * dispatcher re-grab the task before the abort→block lands). Injected by task-dispatch; absent
323
+ * for non-dispatch threads (no owning task). */
324
+ onAbort?: ((info: {
325
+ taskId: string;
326
+ project: string | null;
327
+ reason: string | null;
328
+ }) => Promise<void> | void) | null;
300
329
  /** Per-call lifecycle hooks injected by the caller (task-dispatcher / scheduled-runner / etc.).
301
330
  * Executed AFTER the template's hook at the same phase (template first, extra second) and share
302
331
  * the same execution semantics (HookContext via stdin, insertAgent / targetAgent result).
@@ -35,6 +35,10 @@ export interface RunAgentOptions {
35
35
  /** Recursion depth of the owning thread, surfaced to the spawned agent as CORTEX_THREAD_DEPTH
36
36
  * so the thread_start MCP tool can forward it for the depth guard. */
37
37
  threadDepth?: number | null;
38
+ /** Owning dispatch task id/project, surfaced as CORTEX_TASK_ID / CORTEX_TASK_PROJECT so
39
+ * `cortex-task spawn` can infer the current task as the parent of a child task. */
40
+ taskId?: string | null;
41
+ taskProject?: string | null;
38
42
  onProgress?: ((progress: any) => void) | null;
39
43
  onAssistantMessage?: ((msg: string) => void) | null;
40
44
  onToolUse?: ((name: string, input: any) => void) | null;
@@ -40,8 +40,10 @@ function buildSpawnConfig(options, config, anthropicBaseUrl) {
40
40
  executionId: options.executionId ?? null,
41
41
  useCoreMcp: options.useCoreMcp ?? undefined,
42
42
  threadDepth: options.threadDepth ?? null,
43
+ taskId: options.taskId ?? null,
44
+ taskProject: options.taskProject ?? null,
43
45
  };
44
- const hasContext = !!(ctx.threadId || ctx.profile || ctx.project || ctx.sessionName || ctx.executionId || ctx.useCoreMcp || ctx.threadDepth != null);
46
+ const hasContext = !!(ctx.threadId || ctx.profile || ctx.project || ctx.sessionName || ctx.executionId || ctx.useCoreMcp || ctx.threadDepth != null || ctx.taskId || ctx.taskProject);
45
47
  // Load global rules (no paths frontmatter) and inject as appendSystemPrompt.
46
48
  // Scoped rules (with paths) are handled by the Read/Grep PostToolUse hook.
47
49
  const rules = loadCortexRules();