agents-relay 2.0.255 → 2.0.257

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/README.md +26 -13
  2. package/dist/agent-script-discovery.js +56 -0
  3. package/dist/cli-coordinator.js +71 -0
  4. package/dist/cli-help.js +36 -30
  5. package/dist/cli-job-create.js +37 -4
  6. package/dist/cli.js +21 -12
  7. package/dist/dag-result-contract.js +2 -2
  8. package/dist/{shortcut-stage-contract.js → dag-stage-contract.js} +1 -1
  9. package/dist/dag-task-runtime.js +4 -33
  10. package/dist/dashboard-jel.js +8 -12
  11. package/dist/job-execution-slot.js +3 -11
  12. package/dist/pool.js +28 -15
  13. package/dist/reconciler.js +5 -28
  14. package/dist/relay-job-snapshot-reads.js +2 -5
  15. package/dist/relay-workflow-operations.js +2 -3
  16. package/dist/relayd-control.js +5 -0
  17. package/dist/relayd.js +1 -3
  18. package/dist/runtime-status.js +0 -33
  19. package/dist/script-task-adapter.js +2 -2
  20. package/dist/task-inactivity-watchdog.js +3 -6
  21. package/dist/worker-failure-recovery.js +1 -1
  22. package/dist/workflow/action-ledger.js +1 -1
  23. package/dist/workflow/contracts.js +0 -28
  24. package/dist/workflow/definitions-v2.js +1 -8
  25. package/dist/workflow/runtime.js +0 -9
  26. package/package.json +6 -6
  27. package/skills/agents-relay/SKILL.md +41 -14
  28. package/skills/agents-relay/contracts/event-contract.md +4 -5
  29. package/skills/agents-relay/contracts/task-job-contract.md +35 -1
  30. package/workflow/job-lifecycle.mmd +0 -8
  31. package/workflow/task-lifecycle.mmd +1 -26
  32. package/dist/agent-shortcut.js +0 -587
  33. package/dist/cli-shortcut-local.js +0 -50
  34. package/dist/cli-shortcut.js +0 -267
  35. package/dist/reconciler-shortcut.js +0 -74
  36. package/dist/shortcut-node-revision.js +0 -21
  37. package/dist/shortcut-node-worker.js +0 -144
  38. package/dist/shortcut-review-wake.js +0 -64
  39. package/dist/shortcut-worker-runner.js +0 -64
package/README.md CHANGED
@@ -19,16 +19,15 @@ Relay appends `--handoff-file`, optional `--on-needs-user-file`, and `--cwd`
19
19
  without using a shell. No Neo executable is assumed. Missing/failed executors
20
20
  produce `technical_failure` rather than silently resolving a blocker.
21
21
 
22
- **Unified DAG/Shortcut L3 gate:** `npm run test:l3:shortcut` covers both
23
- legacy in-flight Shortcut recovery (four three-agent scenarios) and the new
24
- ordinary Task Runtime: three Script Tasks without Review; all approvals;
25
- Request Changes and fresh approval for Script and Model Agents; actual Shortcut
26
- CLI activation; Normal-vs-Shortcut DAG equivalence; restart/idempotency;
27
- fork/join concurrency; failed child Task using ordinary Relay recovery; EventBus
28
- wake; and single-Agent Script execution. `Coordinator` only creates dependency-
29
- ready Agent Tasks; each child uses existing Retry, Troubleshooter and Review.
30
- No `NodeExecution`, Git Review commit, or second task scheduler. An inbox
31
- receipt is not user approval. The L3 gate is included in `test:publish`.
22
+ **Unified Coordinator/DAG L3 gate:** `npm run test:l3:dag` exercises four
23
+ three-Agent scenarios: Script without Review, all Approve, Script Request
24
+ Changes then re-Approve, and Model Request Changes then re-Approve. Further
25
+ coverage tests real Job activation, atomically created Coordinator, event-driven
26
+ direct successor dispatch (including parallel branches and resource starvation),
27
+ failed Agent recovery and restart/idempotency. Every Agent is a durable Task;
28
+ `QUEUED` does not impose another global Job scheduling pass when capacity is
29
+ available. The Coordinator has no Worker lease. There is no Shortcut Runner,
30
+ separate DAG state machine, Git Review commit, or hidden approval.
32
31
 
33
32
  **Interactive Review:** Relay owns the generic
34
33
  `review.interactive.begin/wait/fail/abort` lifecycle, execution-bound
@@ -140,7 +139,7 @@ Jobs separate durable lifecycle from derived runtime status. Durable lifecycle i
140
139
 
141
140
  The **Job Execution Lifecycle (JEL)** is Create → Plan → Execute → Final Review → Merge → Completed. All work/recovery Tasks must reach a terminal state (SUCCEEDED, FAILED, or CANCELLED) before Final Review is eligible; terminal failure is evidence for the reviewer, not automatic acceptance. The independent Final Reviewer records findings. A PASS goes to the merge gate; CHANGES_REQUIRED persists findings and starts a minimal Planner N+1 repair round, then another Final Review. No automatic Plan N+1 is created after successful work. Planner and Workers use the discovered `ponytail` Skill to avoid unnecessary tasks without omitting required verification. For operator discussion, call this lifecycle **JEL**.
142
141
 
143
- The Dashboard Job detail includes a **View JEL chart** link. It opens the full-screen graph viewer (Fit, zoom in/out, Ctrl/⌘-wheel zoom, and drag-to-pan) with a read-only Mermaid diagram that shows each persisted Plan, execution round, Final Review (including CHANGES_REQUIRED → Plan N+1), merge stage, and completion status. Every node displays wall-clock elapsed time derived from persisted timestamps (including queued time); missing timing data is labeled **unknown**, not estimated. The JEL popup highlights failed attempts in red, repeated worker attempts (Retry) in purple, and Troubleshooter tasks in amber, as dashed read-only diagnostic branches off their Execute round. Historical failure is shown only when a persisted `recoveryForAttempt` record supports it. The chart never changes Job state. Shortcut-runner jobs display their direct execution path instead of fictitious planning, review, or merge stages.
142
+ The Dashboard Job detail includes a **View JEL chart** link. It opens the full-screen graph viewer (Fit, zoom in/out, Ctrl/⌘-wheel zoom, and drag-to-pan) with a read-only Mermaid diagram that shows each persisted Plan, execution round, Final Review (including CHANGES_REQUIRED → Plan N+1), merge stage, and completion status. Every node displays wall-clock elapsed time derived from persisted timestamps (including queued time); missing timing data is labeled **unknown**, not estimated. The JEL popup highlights failed attempts in red, repeated worker attempts (Retry) in purple, and Troubleshooter tasks in amber, as dashed read-only diagnostic branches off their Execute round. Historical failure is shown only when a persisted `recoveryForAttempt` record supports it. The chart never changes Job state. Plan-free Coordinator Jobs show direct execution without a fictitious Plan, followed by normal Final Review and Git Merge.
144
143
 
145
144
  Lifecycle transition authority lives in the directly renderable canonical flowchart sources linked in [Workflow graph navigation](#workflow-graph-navigation). Git history owns prior graph versions; the working tree contains only the current graph set.
146
145
 
@@ -180,7 +179,7 @@ All task producers use the same story-size contract: `S`≈5 minutes, `M`≈15 m
180
179
 
181
180
  There is no Job scheduling or cron support. Reconciliation resumes objective planning from durable state, including after a missed wake-up or restart. See [objective-driven Jobs](docs/objective-driven-jobs.md).
182
181
 
183
- GitHub projection creates or reuses a display PR after a meaningful source-branch commit. Job creation is always create-only and always enables auto-merge; `--no-auto-merge` is not a `job create` option. Existing Jobs can still change that setting with `job update`. Task execution options belong to `task create`, and the orchestrator may create zero, one, or multiple initial Tasks according to user intent.
182
+ GitHub projection creates or reuses a display PR after a meaningful source-branch commit. Job creation is create-only by default and enables auto-merge unless `--no-auto-merge` is set. A Coordinator may be included atomically by supplying its Graph, input and absolute execution paths. Existing Jobs can still change that setting with `job update`. Task execution options belong to `task create`, and the orchestrator may create zero, one, or multiple initial Tasks according to user intent.
184
183
 
185
184
  Use `job update` for partial mutable metadata changes on an already healthy Job marker/binding:
186
185
 
@@ -304,7 +303,21 @@ npx agents-relay task create --repo OWNER/REPO --pr 5 --id JOB_ID \
304
303
  --input "Research the dashboard UX and write the final report to the declared output file."
305
304
  ~~~
306
305
 
307
- SQLite and the canonical Graphs are authoritative for terminal lifecycle. A remote PR merge/close is an audit observation, not a state transition. Final Review PASS authorizes local Git merge; confirmed local-merge evidence gates `COMPLETED`. The dashboard exposes `/api/jobs` and distinguishes durable Job lifecycle from derived runtime status. The `/api/runtime-summary` Running Tasks, worker, and model totals count only `RUNNING` Tasks belonging to `ACTIVE` Jobs with an execution ID, lease owner, and unexpired lease; old durable RUNNING flags without a current lease are not active workload. Archived direct Shortcut records remain readable, but current Coordinator Jobs use the normal managed Job queue and display. Shortcut artifact hashing accepts a relative file present in both the Project and its canonical Run only if the two resolved files have identical bytes; it records the Run copy and still rejects different contents, path escapes and ambiguous provenance. Daemon startup orphan-recovery must not reclaim externally owned Shortcut Worker leases; only the foreground Shortcut Runner owns their recovery. For model-backed Shortcut nodes, the same caller-configured `--shared-root` (or `AGENTS_RELAY_SHARED_ROOT`) must be supplied to child Worker execution context, not just Shortcut discovery.
306
+ SQLite and the canonical Graphs are authoritative for terminal lifecycle.
307
+ A remote PR merge/close is audit metadata, not completion evidence. Final
308
+ Review PASS authorizes local Git merge; confirmed local-merge evidence gates
309
+ `COMPLETED`. The dashboard distinguishes durable Job lifecycle from derived
310
+ runtime status. `/api/runtime-summary` counts only RUNNING Tasks of ACTIVE
311
+ Jobs with a valid current Worker execution and lease. The Coordinator itself
312
+ has no Worker lease, and every Script/Model DAG node is an ordinary Task.
313
+ Terminal Task events trigger immediate same-Job Reconciler continuation for
314
+ ready successors; the global pool still enforces total Worker capacity.
315
+ A human Preview is Task-bound and never auto-commits Git. The retired
316
+ Shortcut runtime and receipt path are no longer executable or displayed as
317
+ a separate Job mode; normalized historical metadata is ignored. Child Agent
318
+ resolution receives configured `--workspace-root` and `--shared-root` roots
319
+ identically for Script and Model execution.
320
+
308
321
 
309
322
  Relay has no orchestrator worker adapter for new work. Orchestrators are external clients that create/plan durable Tasks; Execution Router selects a real worker route (`codex` or `chatgpt`). The CLI and dashboard do not expose manual orchestrator-only `task start`, `task complete`, or synthetic `record` paths.
310
323
 
@@ -0,0 +1,56 @@
1
+ import { realpath, stat } from 'node:fs/promises';
2
+ import { dirname, basename, join } from 'node:path';
3
+ import { homedir } from 'node:os';
4
+ import { agentSourceLayers, resolveAgentMarkdown } from './agent-content-resolver.js';
5
+ import { BUNDLED_AGENTS_ROOT } from './execution-context.js';
6
+ /** Resolve a local Script Agent using the same Agent inheritance/source rules
7
+ * as the regular Model Task executor. This is not a Shortcut Job runner. */
8
+ export async function discoverScriptAgent(agent, projectPath, sharedRoot, workspaceRoot, globalRoot) {
9
+ let sources;
10
+ try {
11
+ ({ sources } = await resolveAgentMarkdown(agent, BUNDLED_AGENTS_ROOT, projectPath, sharedRoot, agentSourceLayers(projectPath, { sharedRoot, workspaceRoot, globalRoot: globalRoot ?? process.env.AGENTS_HOME ?? join(homedir(), '.agents') })));
12
+ }
13
+ catch (error) {
14
+ if (error instanceof Error && error.message === `Unknown agent ${agent}`)
15
+ return null;
16
+ throw error;
17
+ }
18
+ for (const source of [...sources].reverse()) {
19
+ const agentDir = dirname(source);
20
+ const name = basename(source).replace(/(?:\.agent)?\.md$/, '');
21
+ const shortcutDir = join(agentDir, '.shortcut');
22
+ let shortcutRoot;
23
+ try {
24
+ shortcutRoot = await realpath(shortcutDir);
25
+ }
26
+ catch (error) {
27
+ if (error.code === 'ENOENT')
28
+ continue;
29
+ throw error;
30
+ }
31
+ if (shortcutRoot !== shortcutDir)
32
+ throw new Error(`Agent Script directory symlink escapes Agent source: ${shortcutDir}`);
33
+ const candidate = join(shortcutDir, `${name}.agent.mjs`);
34
+ let actual;
35
+ try {
36
+ actual = await realpath(candidate);
37
+ }
38
+ catch (error) {
39
+ if (error.code === 'ENOENT')
40
+ continue;
41
+ throw error;
42
+ }
43
+ if (dirname(actual) !== shortcutRoot)
44
+ throw new Error(`Agent Script symlink escapes source directory: ${candidate}`);
45
+ if (!(await stat(actual)).isFile())
46
+ throw new Error(`Agent Script is not a regular file: ${candidate}`);
47
+ return actual;
48
+ }
49
+ return null;
50
+ }
51
+ export async function missingScriptAgents(graph, projectPath, sharedRoot, workspaceRoot, globalRoot) {
52
+ const { parseAgentGraph } = await import('./agent-graph.js');
53
+ const nodes = parseAgentGraph(graph).nodes;
54
+ const choices = await Promise.all(nodes.map(async (n) => ({ id: n.id, path: await discoverScriptAgent(n.agent, projectPath, sharedRoot, workspaceRoot, globalRoot) })));
55
+ return choices.filter(n => !n.path).map(n => n.id);
56
+ }
@@ -0,0 +1,71 @@
1
+ import { parseAgentGraph } from './agent-graph.js';
2
+ import { tryTransitionTaskEvent } from './task-transitions.js';
3
+ import { dispatchJobLifecycleSync } from './workflow/lifecycle.js';
4
+ import { noGitHubMode } from './no-github.js';
5
+ import { resolveManagedProjectPath, resolveRepositoryProjectPath, resolveWorkspaceRoot } from './workspace.js';
6
+ import { arg, hasArg, publishWake, storeFor, textOption, withEventBus } from './cli-support.js';
7
+ /** Starts an ordinary DRAFT Job. DAG execution, review and recovery are
8
+ * owned by the same Reconciler and global capacity pool as every other Job. */
9
+ export async function runCoordinatorJobCommand(args, id) {
10
+ if (hasArg(args, '--shortcut-local') || hasArg(args, '--legacy-shortcut-runtime') || hasArg(args, '--event-json') || hasArg(args, '--mode'))
11
+ throw Error('Legacy Shortcut runners and execution modes are removed');
12
+ const loaded = await storeFor(args, false, true);
13
+ if (loaded.localFile !== null || !loaded.store.mutateJob)
14
+ throw Error('Job start requires authoritative SQLite');
15
+ const job = loaded.job, taskId = arg(args, '--task-id');
16
+ if (!taskId)
17
+ throw Error('job run requires --task-id');
18
+ const task = job.tasks.find(t => t.id === taskId);
19
+ if (!task)
20
+ throw Error(`Task ${taskId} not found`);
21
+ const override = hasArg(args, '--agent-graph-file') ? await textOption(args, '--agent-graph', '--agent-graph-file') : undefined;
22
+ if (override)
23
+ parseAgentGraph(override);
24
+ const graph = task.agentGraph ?? override;
25
+ if (!graph)
26
+ throw Error('job run requires a durable Agent Graph Task');
27
+ parseAgentGraph(graph);
28
+ const workspaceRoot = await resolveWorkspaceRoot(arg(args, '--workspace-root') || undefined);
29
+ const checkout = await resolveManagedProjectPath(noGitHubMode(args) ? undefined : job.repository, arg(args, '--project-path') || job.projectPath || '', workspaceRoot);
30
+ const projectPath = resolveRepositoryProjectPath(checkout, job.projectPath);
31
+ const globalRoot = arg(args, '--global-root') || process.env.AGENTS_HOME || undefined;
32
+ const sharedRoot = arg(args, '--shared-root') || process.env.AGENTS_RELAY_SHARED_ROOT || undefined;
33
+ await loaded.store.mutateJob(id, current => {
34
+ const root = current.tasks.find(t => t.id === taskId);
35
+ if (!root)
36
+ throw Error('Coordinator Task disappeared');
37
+ if (root.agentGraph && root.agentGraph !== graph)
38
+ throw Error('Coordinator Graph changed after creation');
39
+ if (!['DRAFT', 'QUEUED', 'RUNNING'].includes(root.state))
40
+ throw Error('Coordinator Task is not startable');
41
+ if (!root.agentGraph) {
42
+ if (root.state !== 'DRAFT' && root.state !== 'QUEUED')
43
+ throw Error('Graph cannot change after execution started');
44
+ root.agentGraph = graph;
45
+ }
46
+ if (root.state === 'DRAFT') {
47
+ if (root.dependencies.length)
48
+ throw Error('Coordinator has unmet dependencies');
49
+ const transition = tryTransitionTaskEvent(root, 'queue', { dependenciesSatisfied: true });
50
+ if (!transition.accepted || transition.target !== 'QUEUED')
51
+ throw Error('Coordinator Task queue denied');
52
+ }
53
+ const ctx = { projectPath, workspaceRoot, ...(sharedRoot ? { sharedRoot } : {}), ...(globalRoot ? { globalRoot } : {}), noGitHub: noGitHubMode(args) };
54
+ const existing = current.graphStartContext;
55
+ if (existing && ['projectPath', 'workspaceRoot', 'sharedRoot', 'globalRoot', 'noGitHub'].some(k => existing[k] !== ctx[k]))
56
+ throw Error('Coordinator start context differs from original binding');
57
+ if (!existing)
58
+ current.graphStartContext = ctx;
59
+ if (current.state === 'DRAFT') {
60
+ const activation = dispatchJobLifecycleSync(current, 'activate');
61
+ if (!activation.accepted || activation.target !== 'ACTIVE')
62
+ throw Error('Job Lifecycle rejected activation');
63
+ }
64
+ else if (current.state !== 'ACTIVE')
65
+ throw Error('Job is not runnable: ' + current.state);
66
+ return current;
67
+ });
68
+ const scheduled = await loaded.store.load(id);
69
+ await withEventBus(args, bus => publishWake(bus, scheduled, taskId, 'Coordinator Job activated'));
70
+ console.log(JSON.stringify({ jobId: id, taskId, scheduled: true, state: scheduled.state, graphRuntime: 'tasks' }, null, 2));
71
+ }
package/dist/cli-help.js CHANGED
@@ -8,7 +8,7 @@ Usage:
8
8
  --no-github: SQLite/Graph-only mode. GitHub auth/API, PR creation, merge and fetch are disabled. Local completion is Graph-owned.
9
9
 
10
10
  Commands:
11
- job create|update|show|list|run|shortcut-receipt|merge|unblock|cancel|pause|resume Manage SQLite-authoritative jobs with optional GitHub PRs
11
+ job create|update|show|list|run|merge|unblock|cancel|pause|resume Manage SQLite-authoritative jobs with optional GitHub PRs
12
12
  task create|update|show|list|revise|classify|complete|retry|unblock|cancel Manage durable tasks
13
13
  review job Request graph-owned review (optional thread override)
14
14
  review interactive Bind, wait, ready, fail or abort a host-owned human review
@@ -34,14 +34,13 @@ Use 'node dist/cli.js' only for explicit local development/demo mode.`,
34
34
  job: `Manage SQLite-authoritative durable jobs.
35
35
 
36
36
  Usage:
37
- npx agents-relay job <create|update|show|list|run|shortcut-receipt|merge|unblock|cancel|pause|resume> [options]
37
+ npx agents-relay job <create|update|show|list|run|merge|unblock|cancel|pause|resume> [options]
38
38
 
39
39
  Actions:
40
- create Create a durable SQLite-authoritative Job
40
+ create Atomically create a durable Job, optionally with its Coordinator DAG Task
41
41
  update Partially update mutable metadata on a healthy existing Job
42
42
  show Show one durable Job
43
- run Activate a create-only Job with a durable Agent Graph Task
44
- shortcut-receipt Atomically record a validated nonhuman result for a persisted wait
43
+ run Activate an ordinary DRAFT Coordinator Graph Job; Relay schedules its Tasks
45
44
  list List managed Jobs in a repository
46
45
  merge Legacy entry point; local Git merge is Graph-owned (no CLI PR merge)
47
46
  unblock Authoritatively invalidate current BLOCKED decisions and trigger replanning/resume
@@ -53,24 +52,20 @@ Common options:
53
52
  --repo OWNER/REPO Required for create; optional Job identity check otherwise
54
53
  --id JOB_ID Durable job identifier
55
54
 
56
- Graph Job activation:
57
- agents-relay job run --id JOB --task-id TASK
58
- [--project-path DIR] [--workspace-root DIR]
59
-
60
- The Job is created DRAFT without a Planner. This command activates its Graph
61
- Task, then the same Relay Reconciler schedules all durable Agent child Tasks.
62
- Final Review uses --review/--no-review; Merge uses --auto-merge/--no-auto-merge. Both are normal Job policies, independent of the Coordinator start.
63
- The --mode shortcut flag is accepted only as a deprecated CLI input alias.
64
- Historical direct Shortcut checkpoints are read for compatibility.
65
-
66
- Record an asynchronous result with:
67
- agents-relay job shortcut-receipt --id JOB --task-id TASK
68
- --node-id NODE --wait-id WAIT --revision REV --execution-id EXECUTION
69
- --output-file result.json --content-sha256 SHA256
70
-
71
- The file must contain the completed shortcut result object. SHA256 is computed
72
- over its canonical JSON content and must equal the persisted wait content hash.
73
-
55
+ Coordinator/DAG creation and activation (no initial Planner required):
56
+ agents-relay job create --repo OWNER/REPO --objective-file job.md
57
+ --coordinator-graph-file /abs/graph.mmd --coordinator-input-file /abs/input.md
58
+ --coordinator-output-path /abs/result.json --coordinator-project-root /abs/project
59
+ --coordinator-workspace-root /abs/workspace [--coordinator-shared-root /abs/shared]
60
+ agents-relay job run --id JOB --task-id coordinator
61
+ [--project-path /abs/project] [--workspace-root /abs/workspace]
62
+
63
+ Creation atomically stores DRAFT Job and Coordinator Task; activation only
64
+ wakes the ordinary Task Reconciler and returns ACTIVE. The Coordinator owns
65
+ one durable Script/Model Task per ready DAG node. After a terminal event,
66
+ its successors are dispatched immediately when capacity permits. Independent
67
+ Final Review and Git Merge policies remain in force. Review previews do not
68
+ create Git commits. No Shortcut Runner or execution mode remains.
74
69
  Example:
75
70
  npx agents-relay job show --id 101`,
76
71
  prompt: `Read-only exact PromptBuilder output for a durable Plan or Task.
@@ -117,19 +112,30 @@ Optional: --thread-id THREAD_ID persists a reviewer override; omitted uses Job r
117
112
 
118
113
  Required: --repo OWNER/REPO and a standalone Job objective. Job ID defaults to an auto-incrementing store-global number; --id may only reference an existing numeric Job.
119
114
  Common: --id JOB_ID (optional), --title TEXT, --objective-file PATH|- (preferred), --objective MARKDOWN (short/simple only), --project-path RELATIVE_PATH, --priority P0|P1|P2|P3, --initial-plan, --review|--no-review, --auto-merge|--no-auto-merge, --tag JSON, --reviewer-thread-id ID, --creator-thread-id ID, --implementation-thread-id ID. --objective and --objective-file are mutually exclusive.
120
- Job creation enables auto-merge and Final Review by default. By default it is create-only; --initial-plan validates the first real Planner round before atomically creating the durable Job and Plan, then publishes the normal wake. A Coordinator Job does not require an initial Plan; neither review nor merge behavior changes based on its start point. Re-running create against an already healthy Job is idempotent and does not mutate its metadata.
115
+ Creation enables auto-merge and Final Review by default. For plan-free DAG
116
+ jobs, pass --coordinator-graph-file GRAPH --coordinator-input-file INPUT
117
+ --coordinator-output-path ABS --coordinator-project-root ABS
118
+ --coordinator-workspace-root ABS [--coordinator-shared-root ABS] to atomically
119
+ persist the Job plus one Coordinator Task. Use job run to activate it.
120
+ Without a Coordinator, create-only DRAFT Jobs can start the Planner with
121
+ --initial-plan. Final Review and Git Merge are independent of how work starts.
122
+ The --no-review and --no-auto-merge policies are separate; creation is
123
+ idempotent and does not rewrite an existing Job.
121
124
 
122
125
  Example:
123
126
  npx agents-relay job create --repo OWNER/REPO --project-path vlog --title "Episode" --objective-file episode.md --initial-plan`,
124
- 'job run': `Activate a create-only Job with a durable Agent Graph Task. No Planner or execution mode is required.
127
+ 'job run': `Activate a DRAFT Job with a durable Coordinator Agent Graph Task. No Planner or execution mode is required.
125
128
 
126
129
  Usage: agents-relay job run --id JOB --task-id TASK [--project-path DIR] [--no-github]
127
130
 
128
- The command activates the normal Job lifecycle and emits a wake-up. The ordinary
129
- Relay Scheduler creates runtime Agent Tasks, runs Script or Model executors,
130
- waits for human review, retries failures and handles completion. A Job may use
131
- ordinary Final Review and Merge policies. The --mode shortcut argument is a
132
- deprecated start alias only; it does not choose an execution engine.`,
131
+ The command activates ordinary Job lifecycle and emits a wake-up. It returns
132
+ ACTIVE without blocking for all Agent Tasks. The same Job Reconciler creates
133
+ Script and Model Tasks, accepts terminal events and directly dispatches newly
134
+ ready DAG successors when capacity is available. QUEUED is only the durable
135
+ capacity/recovery boundary, not a second scheduled Job. Human review waits,
136
+ retry and recovery use the normal Task lifecycle. Final Review and Git Merge
137
+ remain ordinary Job policies. No Git commit occurs on interactive review.
138
+ There is no Shortcut execution mode.`,
133
139
  'job update': `Partially update mutable metadata on a healthy existing Job.
134
140
 
135
141
  Required: --id JOB_ID. Optional: --repo OWNER/REPO verifies the stored Job identity.
@@ -1,12 +1,25 @@
1
1
  import { allocateEntityId, isGeneratedEntityId } from './job-task-id-sequence.js';
2
2
  import { openLocalManagedStore } from './local-managed-store.js';
3
- import { createJobEntity } from './workflow/entity-creation.js';
3
+ import { createJobEntity, createTaskEntity } from './workflow/entity-creation.js';
4
+ import { parseAgentGraph } from './agent-graph.js';
5
+ import { taskOverallTimeoutMs } from './types.js';
6
+ import { isAbsolute } from 'node:path';
4
7
  import { normalizeThreadId } from './reviewer-thread.js';
5
8
  import { discoverLocalRelayStoreSnapshots, relayStoreDirectory } from './relay-store.js';
6
9
  /** Create a local SQLite-authoritative Job; external PR metadata is optional compatibility data. */
7
10
  export async function ensureManagedGitHubJob(_client, repositoryName, _trustedAuthors, options) {
8
11
  if (options.id && !/^[1-9][0-9]*$/.test(options.id))
9
12
  throw new Error('Job ID must be a positive decimal integer');
13
+ if (options.coordinator) {
14
+ const c = options.coordinator;
15
+ if (!c.graph?.trim() || !c.input?.trim())
16
+ throw Error('Coordinator requires nonempty graph and input');
17
+ parseAgentGraph(c.graph);
18
+ if (!isAbsolute(c.outputPath) || !isAbsolute(c.projectRoot) || !isAbsolute(c.workspaceRoot) ||
19
+ (c.sharedRoot !== undefined && !isAbsolute(c.sharedRoot)) ||
20
+ (c.globalRoot !== undefined && !isAbsolute(c.globalRoot)))
21
+ throw Error('Coordinator paths must be absolute');
22
+ }
10
23
  const directory = options.storeDirectory ?? relayStoreDirectory();
11
24
  const knownJobs = (await discoverLocalRelayStoreSnapshots(directory)).flatMap(snapshot => snapshot.jobs);
12
25
  const id = options.id || allocateEntityId(directory, repositoryName, 'job', options.idempotencyKey, new Set(knownJobs.map(job => job.id)));
@@ -26,6 +39,13 @@ export async function ensureManagedGitHubJob(_client, repositoryName, _trustedAu
26
39
  throw new Error('Automatically allocated Job ID unexpectedly belongs to an existing Job');
27
40
  if (options.idempotencyKey && ((options.objective && options.objective !== existing.objective) || (options.projectPath && options.projectPath !== existing.projectPath) || (options.title && options.title !== existing.title)))
28
41
  throw new Error('Job idempotency key reused for a different Job definition');
42
+ if (options.coordinator) {
43
+ const task = existing.tasks.find(task => task.id === 'coordinator');
44
+ if (!task || task.agentGraph !== options.coordinator.graph || task.input !== options.coordinator.input ||
45
+ task.output?.kind !== 'file' || task.output.path !== options.coordinator.outputPath ||
46
+ existing.graphStartContext?.projectPath !== options.coordinator.projectRoot)
47
+ throw Error('Coordinator idempotency key reused for a different Graph or Run');
48
+ }
29
49
  return { job: existing, pr: { ...placeholder, number: existing.prNumber } };
30
50
  }
31
51
  if (options.id && isGeneratedEntityId(id, repositoryName, 'job'))
@@ -53,10 +73,9 @@ export async function ensureManagedGitHubJob(_client, repositoryName, _trustedAu
53
73
  description: pr.body || undefined,
54
74
  priority: options.priority ?? 'P2',
55
75
  tag: options.tag,
56
- autoMerge: options.legacyShortcutBootstrap ? false : options.autoMerge ?? true,
76
+ autoMerge: options.autoMerge ?? true,
57
77
  ...(localMergeSource ? { localMerge: { sourceRef: localMergeSource, targetRef: 'refs/heads/main', status: 'pending' } } : {}),
58
- reviewEnabled: options.legacyShortcutBootstrap ? false : options.reviewEnabled ?? true,
59
- ...(options.legacyShortcutBootstrap ? { executionMode: 'shortcut', contentOnly: true } : {}),
78
+ reviewEnabled: options.reviewEnabled ?? true,
60
79
  ...(options.reviewerThreadId
61
80
  ? { reviewerThreadId: normalizeThreadId(options.reviewerThreadId, 'reviewer thread ID') }
62
81
  : {}),
@@ -72,7 +91,21 @@ export async function ensureManagedGitHubJob(_client, repositoryName, _trustedAu
72
91
  createdAt: now,
73
92
  updatedAt: now,
74
93
  tasks: [],
94
+ ...(options.coordinator ? { graphStartContext: { projectPath: options.coordinator.projectRoot,
95
+ workspaceRoot: options.coordinator.workspaceRoot,
96
+ ...(options.coordinator.sharedRoot ? { sharedRoot: options.coordinator.sharedRoot } : {}),
97
+ ...(options.coordinator.globalRoot ? { globalRoot: options.coordinator.globalRoot } : {}),
98
+ noGitHub: options.noGitHub === true } } : {}),
75
99
  });
100
+ if (options.coordinator) {
101
+ const c = options.coordinator;
102
+ job.tasks.push(createTaskEntity(job, { jobId: id, id: 'coordinator', title: 'Coordinator',
103
+ parentTaskId: null, kind: 'work', agentGraph: c.graph, input: c.input,
104
+ output: { kind: 'file', path: c.outputPath }, adapter: 'codex', capabilities: [],
105
+ dependencies: [], attempt: 0, maxAttempts: 3, leaseOwner: null, leaseExpiresAt: null,
106
+ executionId: null, threadId: null, result: null, error: null,
107
+ timeoutMs: taskOverallTimeoutMs('L'), createdAt: now, updatedAt: now }));
108
+ }
76
109
  if (options.persist !== false) {
77
110
  if (local.store.createJobIfAbsent)
78
111
  await local.store.createJobIfAbsent(job);
package/dist/cli.js CHANGED
@@ -50,8 +50,7 @@ import { dependencyValidityFromArgs, recoveryDiagnosisFromArgs, workerTaskFromAr
50
50
  import { requestTroubleshooterEscalation, resumeTroubleshooter } from './task-recovery.js';
51
51
  import { pauseJob, resumeJob } from './job-pause.js';
52
52
  export { ensureManagedGitHubJob } from './cli-job-create.js';
53
- import { recordShortcutReceiptCommand, runShortcutJobCommand } from './cli-shortcut.js';
54
- import { runLocalShortcutBinding } from './cli-shortcut-local.js';
53
+ import { runCoordinatorJobCommand } from './cli-coordinator.js';
55
54
  import { runContextCommand } from './cli-context.js';
56
55
  async function runManagedTaskCommand(action, args) {
57
56
  const jobId = arg(args, '--id');
@@ -80,7 +79,7 @@ async function runManagedTaskCommand(action, args) {
80
79
  }
81
80
  async function runTaskCommand(action, args) {
82
81
  if (hasArg(args, '--shortcut-local'))
83
- return runLocalShortcutBinding('task', action, args);
82
+ throw Error('Legacy Shortcut local binding is removed');
84
83
  if (!['create', 'update', 'show', 'context', 'events', 'comment', 'comments', 'list', 'retry', 'recover', 'unblock', 'escalate', 'resume-troubleshooter', 'cancel', 'supersede', 'classify', 'revise'].includes(action))
85
84
  throw new Error(usage);
86
85
  if (action === 'revise') {
@@ -392,11 +391,11 @@ async function runTaskCommand(action, args) {
392
391
  }
393
392
  async function runJobCommand(action, args) {
394
393
  if (hasArg(args, '--shortcut-local'))
395
- return runLocalShortcutBinding('job', action, args);
394
+ throw Error('Legacy Shortcut local binding is removed');
396
395
  const obsolete = ['--content-only', '--no-content-only', '--shortcut-execution'].find(flag => hasArg(args, flag));
397
396
  if (obsolete && ['create', 'update'].includes(action))
398
397
  throw new Error(`${obsolete} is obsolete; configure normal --review/--no-review and --auto-merge/--no-auto-merge independently`);
399
- if (!['create', 'update', 'show', 'list', 'merge', 'unblock', 'cancel', 'pause', 'resume', 'run', 'shortcut-receipt'].includes(action))
398
+ if (!['create', 'update', 'show', 'list', 'merge', 'unblock', 'cancel', 'pause', 'resume', 'run'].includes(action))
400
399
  throw new Error(usage);
401
400
  const repo = action === 'create' ? repository(args) : arg(args, '--repo');
402
401
  if (action !== 'create')
@@ -438,20 +437,30 @@ async function runJobCommand(action, args) {
438
437
  const objective = createObjective ?? '';
439
438
  if (hasArg(args, '--local-merge-source') !== hasArg(args, '--local-merge-target'))
440
439
  throw new Error('Supply both --local-merge-source and --local-merge-target');
440
+ const coordinatorFile = arg(args, '--coordinator-graph-file');
441
+ const coordinatorOutput = arg(args, '--coordinator-output-path');
442
+ const coordinatorRoot = arg(args, '--coordinator-project-root');
443
+ const coordinatorWorkspace = arg(args, '--coordinator-workspace-root');
444
+ const hasCoordinator = Boolean(coordinatorFile || coordinatorOutput || coordinatorRoot || coordinatorWorkspace || hasArg(args, '--coordinator-input-file'));
445
+ if (hasCoordinator && !(coordinatorFile && coordinatorOutput && coordinatorRoot && coordinatorWorkspace && hasArg(args, '--coordinator-input-file')))
446
+ throw Error('Coordinator requires graph-file, input-file, output-path, project-root and workspace-root');
447
+ if (hasCoordinator && hasArg(args, '--initial-plan'))
448
+ throw Error('Coordinator starts directly without a Planner');
449
+ const coordinator = hasCoordinator ? { graph: await textOption(args, '--coordinator-graph', '--coordinator-graph-file'),
450
+ input: await textOption(args, '--coordinator-input', '--coordinator-input-file'),
451
+ outputPath: coordinatorOutput, projectRoot: coordinatorRoot, workspaceRoot: coordinatorWorkspace,
452
+ sharedRoot: arg(args, '--coordinator-shared-root') || undefined } : undefined;
441
453
  const result = await relayControlCommand(args, { command: 'job.create', repository: repo, initialPlan: hasArg(args, '--initial-plan'), options: {
442
454
  id: id || undefined, idempotencyKey: arg(args, '--idempotency-key') || undefined, title: arg(args, '--title') || undefined, objective: objective || undefined, projectPath: arg(args, '--project-path') || undefined,
443
455
  priority: priority(args), tag: jobTagFromArgs(args), reviewEnabled: !hasArg(args, '--no-review'), autoMerge: !hasArg(args, '--no-auto-merge'), continuation: continuation(args),
456
+ coordinator,
444
457
  reviewerThreadId: hasArg(args, '--reviewer-thread-id') ? arg(args, '--reviewer-thread-id') : undefined, creatorThreadId: hasArg(args, '--creator-thread-id') ? arg(args, '--creator-thread-id') : undefined, implementationThreadId: hasArg(args, '--implementation-thread-id') ? arg(args, '--implementation-thread-id') : undefined,
445
458
  } });
446
459
  console.log(JSON.stringify(result, null, 2));
447
460
  return;
448
461
  }
449
462
  if (action === 'run') {
450
- await runShortcutJobCommand(args, id, (store, bus) => runtime(store, args, bus, codexAndZaiUsageRegistry(), true));
451
- return;
452
- }
453
- if (action === 'shortcut-receipt') {
454
- await recordShortcutReceiptCommand(args, id);
463
+ await runCoordinatorJobCommand(args, id);
455
464
  return;
456
465
  }
457
466
  const job = await relayControlJob(args, id);
@@ -525,12 +534,12 @@ async function runJobCommand(action, args) {
525
534
  console.log(JSON.stringify(await relayControlCommand(args, { command: 'job.update', jobId: id, patch }), null, 2));
526
535
  }
527
536
  export function runtimePlanner(args) { const plannerCommand = arg([...args], '--planner-command'); const modelRuntime = arg([...args], '--codex', 'codex'); return plannerCommand ? new CommandObjectivePlanner(plannerCommand) : new AgentObjectivePlanner(modelRuntime); }
528
- export function runtime(store, args, bus, usageRegistry = codexAndZaiUsageRegistry(), shortcutRunnerOwner = false) {
537
+ export function runtime(store, args, bus, usageRegistry = codexAndZaiUsageRegistry()) {
529
538
  const emit = (event) => { process.stderr.write(`${JSON.stringify(event)}\n`); };
530
539
  const modelRuntime = arg(args, '--codex', 'codex');
531
540
  const policy = chatGptTabClosePolicy(args);
532
541
  const planner = runtimePlanner(args);
533
- return new Reconciler(store, { shortcutRunnerOwner, noGitHub: noGitHubMode(args), owner: arg(args, '--owner', `cli-${process.pid}`), maxConcurrent: Number(arg(args, '--concurrency', '4')), leaseMs: Number(arg(args, '--lease-ms', '300000')), adapters: [new CodexAdapter(modelRuntime), new ChatGptAdapter({ tabClosePolicy: policy }), new ZAdapter()], continuations: [new CodexThreadContinuation(modelRuntime), new CommandContinuation(), new WebhookContinuation()], planner, usageSnapshotProvider: () => usageRegistry.snapshot(), decisionEngine: executionDecisionEngine(), decisionMode: decisionMode(), reviewer: runtimeReviewer(args), eventBus: bus, emit, chatgptTabClosePolicy: policy, executionContextRoots: { workspaceRoot: arg(args, '--workspace-root') || process.env.AGENTS_RELAY_WORKSPACE_ROOT, sharedRoot: arg(args, '--shared-root') || process.env.AGENTS_RELAY_SHARED_ROOT || undefined, globalRoot: arg(args, '--global-root') || process.env.AGENTS_HOME || undefined }, projectPathForJob: async (job, task) => {
542
+ return new Reconciler(store, { noGitHub: noGitHubMode(args), owner: arg(args, '--owner', `cli-${process.pid}`), maxConcurrent: Number(arg(args, '--concurrency', '4')), leaseMs: Number(arg(args, '--lease-ms', '300000')), adapters: [new CodexAdapter(modelRuntime), new ChatGptAdapter({ tabClosePolicy: policy }), new ZAdapter()], continuations: [new CodexThreadContinuation(modelRuntime), new CommandContinuation(), new WebhookContinuation()], planner, usageSnapshotProvider: () => usageRegistry.snapshot(), decisionEngine: executionDecisionEngine(), decisionMode: decisionMode(), reviewer: runtimeReviewer(args), eventBus: bus, emit, chatgptTabClosePolicy: policy, executionContextRoots: { workspaceRoot: arg(args, '--workspace-root') || process.env.AGENTS_RELAY_WORKSPACE_ROOT, sharedRoot: arg(args, '--shared-root') || process.env.AGENTS_RELAY_SHARED_ROOT || undefined, globalRoot: arg(args, '--global-root') || process.env.AGENTS_HOME || undefined }, projectPathForJob: async (job, task) => {
534
543
  const workspaceRoot = await resolveWorkspaceRoot(arg(args, '--workspace-root') || undefined);
535
544
  const canonical = await resolveManagedProjectPath(noGitHubMode(args) ? undefined : job.repository, arg(args, '--project-path'), workspaceRoot);
536
545
  if (!(task ? taskRequiresManagedWorktree(job, task) : Boolean(job.localMerge?.sourceRef)))
@@ -2,7 +2,7 @@ import { readFile } from 'node:fs/promises';
2
2
  import { dirname } from 'node:path';
3
3
  import { once } from 'node:events';
4
4
  import { spawnOwnedProcess } from './owned-process.js';
5
- import { validateShortcutStageGate } from './shortcut-stage-contract.js';
5
+ import { validateDAGStageGate } from './dag-stage-contract.js';
6
6
  /** Validate an Agent DAG Task's required on-disk result before accepting
7
7
  * task.completed. Invalid output is an ordinary Task failure and enters the
8
8
  * existing Troubleshooter path; it must not strand a running Coordinator. */
@@ -28,7 +28,7 @@ export async function dagCompletionError(task, projectPath) {
28
28
  return 'DAG Agent result must contain a list or object of artifacts';
29
29
  if (projectPath && task.agentName) {
30
30
  try {
31
- await validateShortcutStageGate({ projectPath, agent: task.agentName, runPath: dirname(dirname(task.output.path)),
31
+ await validateDAGStageGate({ projectPath, agent: task.agentName, runPath: dirname(dirname(task.output.path)),
32
32
  execute: async (args, cwd) => {
33
33
  const abort = AbortSignal.timeout(300_000);
34
34
  const child = spawnOwnedProcess(args[0], args.slice(1), { invocation: 'dag.stage-validation', signal: abort,
@@ -3,7 +3,7 @@
3
3
  import { readFile, realpath } from 'node:fs/promises';
4
4
  import { resolve, relative, isAbsolute, sep, join } from 'node:path';
5
5
  const within = (root, target) => { const rel = relative(root, target); return rel === '' || (rel !== '..' && !rel.startsWith('..' + sep) && !isAbsolute(rel)); };
6
- export async function validateShortcutStageGate(options) {
6
+ export async function validateDAGStageGate(options) {
7
7
  const root = await realpath(options.projectPath);
8
8
  let manifest;
9
9
  try {
@@ -3,18 +3,11 @@ import { dirname, isAbsolute, join } from 'node:path';
3
3
  import { mkdir, readFile } from 'node:fs/promises';
4
4
  import { taskOverallTimeoutMs } from './types.js';
5
5
  import { parseAgentGraph } from './agent-graph.js';
6
- import { discoverShortcut } from './agent-shortcut.js';
6
+ import { discoverScriptAgent } from './agent-script-discovery.js';
7
7
  import { createTaskEntity } from './workflow/entity-creation.js';
8
8
  import { tryTransitionTaskEvent } from './task-transitions.js';
9
- import { dispatchJobLifecycleSync } from './workflow/lifecycle.js';
10
9
  export function dagChildId(parentTaskId, nodeId) { return `dag-${parentTaskId}-${nodeId}`; }
11
- export function unifiedDAG(job, task) {
12
- if (!task.agentGraph)
13
- return false;
14
- if (job.executionMode !== 'shortcut')
15
- return true;
16
- return task.result?.data?.dag?.version === 1;
17
- }
10
+ export function unifiedDAG(_job, task) { return Boolean(task.agentGraph); }
18
11
  export function dagCoordinator(task) { return Boolean(task.agentGraph && task.result?.data?.dag?.version === 1); }
19
12
  const sha = (s) => createHash('sha256').update(s).digest('hex');
20
13
  const out = (task) => {
@@ -94,7 +87,7 @@ export async function reconcileDAGTasks(options) {
94
87
  predecessorOutputs[parents[i]] = value;
95
88
  }
96
89
  const node = graph.nodes.find(n => n.id === nodeId);
97
- const script = await discoverShortcut(node.agent, projectPath, options.roots?.sharedRoot ?? undefined, options.roots?.workspaceRoot ?? undefined, options.roots?.globalRoot ?? undefined);
90
+ const script = await discoverScriptAgent(node.agent, projectPath, options.roots?.sharedRoot ?? undefined, options.roots?.workspaceRoot ?? undefined, options.roots?.globalRoot ?? undefined);
98
91
  const childOut = join(root, '.dag-node-results', childId + '.json');
99
92
  let supplied = { taskInput: parent.input };
100
93
  try {
@@ -147,7 +140,6 @@ export async function reconcileDAGTasks(options) {
147
140
  });
148
141
  }
149
142
  }
150
- await completeContentJobIfEligible(store, jobId);
151
143
  }
152
144
  /** Human Request Changes on a scripted Agent goes to its model Worker within
153
145
  * the SAME durable Task. Approval goes back to the Script for stage validation.
@@ -185,30 +177,9 @@ export async function selectDAGReviewExecutors(store, jobId) {
185
177
  /** Run the DAG projection at the ordinary Reconciler scheduling boundary. */
186
178
  export async function reconcileDAGSchedule(options) {
187
179
  if (!options.job.tasks.some(t => unifiedDAG(options.job, t))) {
188
- await completeContentJobIfEligible(options.store, options.jobId);
189
- return options.store.load(options.jobId);
180
+ return options.job;
190
181
  }
191
182
  await reconcileDAGTasks(options);
192
183
  await selectDAGReviewExecutors(options.store, options.jobId);
193
184
  return options.store.load(options.jobId);
194
185
  }
195
- /** Content completion is independent of the Job activation source. Its legal
196
- * ACTIVE -> COMPLETED transition belongs to the canonical Job graph. */
197
- export async function completeContentJobIfEligible(store, jobId) {
198
- if (!store.mutateJob)
199
- return;
200
- const eligible = (job) => job.state === 'ACTIVE' && job.contentOnly === true && job.prNumber === 0 &&
201
- !job.localMerge && job.autoMerge === false && job.reviewEnabled === false && !job.review && !(job.plans?.length) &&
202
- job.tasks.length > 0 && job.tasks.every(t => t.state === 'SUCCEEDED');
203
- const snapshot = await store.load(jobId);
204
- if (!eligible(snapshot))
205
- return;
206
- await store.mutateJob(jobId, job => {
207
- if (!eligible(job))
208
- return job;
209
- const decision = dispatchJobLifecycleSync(job, 'content.completed', { contentCompletionAllowed: true });
210
- if (!decision.accepted || decision.target !== 'COMPLETED')
211
- throw Error('Content Job completion rejected by canonical Job lifecycle');
212
- return job;
213
- });
214
- }
@@ -93,15 +93,6 @@ export function jobJelDiagram(job) {
93
93
  const jobEnd = ['COMPLETED', 'CANCELLED'].includes(job.state || '') ? job.updatedAt : 'NOW';
94
94
  const firstStart = plans[0]?.createdAt || (job.tasks || []).map(task => task.createdAt).filter(Boolean).sort()[0];
95
95
  node('created', 'Create / recorded', elapsed(job.createdAt, firstStart || jobEnd));
96
- if (job.executionMode === 'shortcut') {
97
- const work = tasks.filter(task => !isReviewer(task) && !isTroubleshooter(task));
98
- node('execute', 'Shortcut execute / ' + workLabel(work), workElapsed(work));
99
- diagnostics('execute', 'shortcut', work, tasks.filter(isTroubleshooter));
100
- node('finished', 'Job / ' + state(job.state, 'UNKNOWN'), elapsed(job.createdAt, jobEnd));
101
- edge('created', 'execute');
102
- edge('execute', 'finished');
103
- return finish();
104
- }
105
96
  const rounds = plans.length ? plans : [{ id: '', round: 1, status: 'NOT STARTED', generatedTaskIds: [] }];
106
97
  let previous = 'created';
107
98
  for (let i = 0; i < rounds.length; i++) {
@@ -113,7 +104,8 @@ export function jobJelDiagram(job) {
113
104
  const reviewId = 'review_' + suffix;
114
105
  const assigned = new Set(Array.isArray(plan.generatedTaskIds) ? plan.generatedTaskIds : []);
115
106
  const work = (plans.length ? tasks.filter(task => !isReviewer(task) && !isTroubleshooter(task) && (task.planningDecisionId === plan.id || assigned.has(task.id || ''))) : tasks.filter(task => !isReviewer(task) && !isTroubleshooter(task)));
116
- node(planId, 'Plan ' + number + ' / ' + state(plan.status, 'NOT STARTED'), elapsed(plan.createdAt, plan.status === 'PLANNING' ? 'NOW' : plan.updatedAt));
107
+ if (plans.length)
108
+ node(planId, 'Plan ' + number + ' / ' + state(plan.status, 'NOT STARTED'), elapsed(plan.createdAt, plan.status === 'PLANNING' ? 'NOW' : plan.updatedAt));
117
109
  node(executeId, 'Execute ' + number + ' / ' + workLabel(work), workElapsed(work));
118
110
  const workIds = new Set(work.map(task => task.id));
119
111
  const troubleshoot = tasks.filter(task => isTroubleshooter(task) &&
@@ -126,8 +118,12 @@ export function jobJelDiagram(job) {
126
118
  const reviewTasks = tasks.filter(task => isReviewer(task) && instant(task.createdAt) !== null && instant(plan.createdAt) !== null &&
127
119
  instant(task.createdAt) >= instant(plan.createdAt) && (!nextPlan?.createdAt || (instant(nextPlan.createdAt) !== null && instant(task.createdAt) < instant(nextPlan.createdAt))));
128
120
  node(reviewId, 'Final Review ' + number + ' / ' + review, workElapsed(reviewTasks));
129
- edge(previous, planId, i > 0 && plan.trigger?.source === 'review' ? 'changes required' : '');
130
- edge(planId, executeId);
121
+ if (plans.length) {
122
+ edge(previous, planId, i > 0 && plan.trigger?.source === 'review' ? 'changes required' : '');
123
+ edge(planId, executeId);
124
+ }
125
+ else
126
+ edge(previous, executeId);
131
127
  edge(executeId, reviewId);
132
128
  previous = reviewId;
133
129
  }