@luminascale/shepherd 0.0.0-stage → 0.6.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.agents/agents/README.md +12 -0
- package/.agents/agents/planner.md +38 -0
- package/.agents/agents/reviewer.md +38 -0
- package/.agents/agents/scout.md +43 -0
- package/.agents/agents/worker.md +33 -0
- package/.agents/skills/smoke-test/SKILL.md +155 -0
- package/.agents/skills/smoke-test/references/forensics.md +46 -0
- package/.agents/skills/smoke-test/scripts/live-smoke-poll.mjs +130 -0
- package/.github/workflows/publish.yml +77 -0
- package/.pi/prompts/release.md +21 -0
- package/.prettierrc +10 -0
- package/AGENTS.md +88 -0
- package/CONTRIBUTING.md +177 -0
- package/LICENSE +201 -0
- package/README.md +397 -2
- package/docs/README.md +26 -0
- package/docs/guides/agent-definitions.md +42 -0
- package/docs/guides/diagnostics.md +199 -0
- package/docs/guides/installation.md +61 -0
- package/docs/guides/tool-reference.md +55 -0
- package/docs/manual-tests/ping-pong-peer-messaging.md +147 -0
- package/docs/plans/agent-labels.md +257 -0
- package/docs/plans/architecture.md +110 -0
- package/docs/plans/settings-scope.md +163 -0
- package/docs/plans/tool-surface-split.md +278 -0
- package/docs/reference/dictionary +26 -0
- package/docs/releasing.md +47 -0
- package/docs/specs/005-agent-messaging-and-task-lifecycle/baseline.md +115 -0
- package/docs/specs/005-agent-messaging-and-task-lifecycle/handoff.md +564 -0
- package/docs/specs/005-agent-messaging-and-task-lifecycle/phase10-notes.md +109 -0
- package/docs/specs/005-agent-messaging-and-task-lifecycle/phase6-notes.md +69 -0
- package/docs/specs/005-agent-messaging-and-task-lifecycle/phase7-notes.md +100 -0
- package/docs/specs/005-agent-messaging-and-task-lifecycle/phase8-notes.md +127 -0
- package/docs/specs/005-agent-messaging-and-task-lifecycle/phase9-notes.md +104 -0
- package/docs/specs/005-agent-messaging-and-task-lifecycle/plan.md +1093 -0
- package/docs/specs/005-agent-messaging-and-task-lifecycle/spec.md +583 -0
- package/docs/specs/005-agent-messaging-and-task-lifecycle/tasks.md +838 -0
- package/docs/specs/006-shepherd-tool-rendering/plan.md +175 -0
- package/docs/specs/006-shepherd-tool-rendering/spec.md +469 -0
- package/index.ts +602 -0
- package/package.json +112 -4
- package/scripts/capture-system-prompt.mjs +45 -0
- package/scripts/extract-pi-system-prompt.mjs +277 -0
- package/scripts/host-impact.mjs +74 -0
- package/scripts/resolve-agent.mjs +43 -0
- package/scripts/show-shepherd-orchestrator.mjs +58 -0
- package/scripts/show-shepherd-prompt.mjs +96 -0
- package/scripts/verify-suites.mjs +67 -0
- package/specs/001-artifacts/spec.md +436 -0
- package/specs/002-simplify-agent-orchestration/plan.md +287 -0
- package/specs/002-simplify-agent-orchestration/spec.md +323 -0
- package/specs/002-simplify-agent-orchestration/tasks.md +212 -0
- package/specs/003-orchestrator-session-artifacts/plan.md +396 -0
- package/specs/003-orchestrator-session-artifacts/spec.md +453 -0
- package/specs/003-orchestrator-session-artifacts/tasks.md +141 -0
- package/specs/004-asynchronous-prompt-watchers/plan.md +139 -0
- package/specs/004-asynchronous-prompt-watchers/spec.md +202 -0
- package/specs/004-asynchronous-prompt-watchers/tasks.md +126 -0
- package/specs/005-per-workspace-settings/plan.md +230 -0
- package/specs/005-per-workspace-settings/spec.md +368 -0
- package/specs/005-per-workspace-settings/tasks.md +178 -0
- package/specs/006-dual-runtime-herdr-durable/intent.md +86 -0
- package/specs/006-dual-runtime-herdr-durable/journal.md +80 -0
- package/specs/006-dual-runtime-herdr-durable/plan.md +242 -0
- package/specs/006-dual-runtime-herdr-durable/spec.md +389 -0
- package/specs/006-dual-runtime-herdr-durable/tasks.md +199 -0
- package/specs/007-unwatched-completion-notice/journal.md +145 -0
- package/specs/007-unwatched-completion-notice/plan.md +186 -0
- package/specs/007-unwatched-completion-notice/spec.md +284 -0
- package/specs/007-unwatched-completion-notice/tasks.md +147 -0
- package/specs/008-remote-machine-sheep/intent.md +174 -0
- package/specs/008-remote-machine-sheep/journal.md +57 -0
- package/specs/008-remote-machine-sheep/prerequisites.md +219 -0
- package/specs/009-hc-runtime/intent.md +44 -0
- package/specs/009-hc-runtime/plan.md +49 -0
- package/specs/009-hc-runtime/spec.md +118 -0
- package/specs/009-hc-runtime/tasks.md +62 -0
- package/specs/010-unseen-watch-parity/intent.md +57 -0
- package/specs/010-unseen-watch-parity/journal.md +172 -0
- package/specs/010-unseen-watch-parity/plan.md +74 -0
- package/specs/010-unseen-watch-parity/spec.md +191 -0
- package/specs/010-unseen-watch-parity/tasks.md +119 -0
- package/specs/011-hc-background-poll/intent.md +57 -0
- package/specs/011-hc-background-poll/journal.md +95 -0
- package/specs/011-hc-background-poll/plan.md +87 -0
- package/specs/011-hc-background-poll/spec.md +141 -0
- package/specs/011-hc-background-poll/tasks.md +83 -0
- package/specs/012-steer-default/intent.md +12 -0
- package/specs/012-steer-default/journal.md +40 -0
- package/specs/012-steer-default/plan.md +7 -0
- package/specs/012-steer-default/spec.md +42 -0
- package/specs/012-steer-default/tasks.md +6 -0
- package/specs/013-opencode-shepherd/handoff-t011.md +94 -0
- package/specs/013-opencode-shepherd/intent.md +59 -0
- package/specs/013-opencode-shepherd/plan.md +204 -0
- package/specs/013-opencode-shepherd/spec.md +258 -0
- package/specs/013-opencode-shepherd/tasks.md +263 -0
- package/src/core/artifact-sessions.ts +835 -0
- package/src/core/config.ts +329 -0
- package/src/core/discovery.ts +342 -0
- package/src/core/herdr.ts +1 -0
- package/src/core/host.ts +77 -0
- package/src/core/ids.ts +78 -0
- package/src/core/lifecycle.ts +1 -0
- package/src/core/messaging.ts +1 -0
- package/src/core/migration.ts +55 -0
- package/src/core/orchestration.ts +1 -0
- package/src/core/types.ts +143 -0
- package/src/core/unseen-completions.ts +114 -0
- package/src/extension/cli.ts +417 -0
- package/src/extension/config.ts +1 -0
- package/src/extension/settings-ui.ts +296 -0
- package/src/extension/shepherd-done.ts +768 -0
- package/src/extension/shepherd.ts +2548 -0
- package/src/extension/system-prompt.ts +38 -0
- package/src/extension/unseen-completions.ts +237 -0
- package/src/opencode/actions.ts +794 -0
- package/src/opencode/bridge.ts +777 -0
- package/src/opencode/display.ts +36 -0
- package/src/opencode/fieldnotes.ts +60 -0
- package/src/opencode/host.ts +62 -0
- package/src/opencode/orphans.ts +162 -0
- package/src/opencode/server.ts +458 -0
- package/src/runtimes/backend.ts +119 -0
- package/src/runtimes/detect.ts +102 -0
- package/src/runtimes/hc/hc.ts +527 -0
- package/src/runtimes/hc/runtime.ts +1898 -0
- package/src/runtimes/herdr/herdr.ts +912 -0
- package/src/runtimes/herdr/lifecycle.ts +1712 -0
- package/src/runtimes/herdr/messaging.ts +703 -0
- package/src/runtimes/herdr/orchestration.ts +1583 -0
- package/src/runtimes/herdr/runtime.ts +224 -0
- package/src/runtimes/runtime.ts +133 -0
- package/src/runtimes/settle-observations.ts +114 -0
- package/test/fixtures/context-project/AGENTS.md +2 -0
- package/test/fixtures/home/.agents/agents/same.md +6 -0
- package/test/fixtures/home/.agents/agents/shared-only.md +6 -0
- package/test/fixtures/home/.pi/agent/agents/invalid-thinking.md +6 -0
- package/test/fixtures/home/.pi/agent/agents/model-empty.md +7 -0
- package/test/fixtures/home/.pi/agent/agents/model-explicit.md +7 -0
- package/test/fixtures/home/.pi/agent/agents/omit-context-absent.md +5 -0
- package/test/fixtures/home/.pi/agent/agents/omit-context-false.md +6 -0
- package/test/fixtures/home/.pi/agent/agents/omit-context-invalid.md +6 -0
- package/test/fixtures/home/.pi/agent/agents/omit-context-true.md +6 -0
- package/test/fixtures/home/.pi/agent/agents/omit-false.md +6 -0
- package/test/fixtures/home/.pi/agent/agents/omit-invalid.md +6 -0
- package/test/fixtures/home/.pi/agent/agents/omit-pi-docs.md +7 -0
- package/test/fixtures/home/.pi/agent/agents/omit-true.md +6 -0
- package/test/fixtures/home/.pi/agent/agents/only-user.md +9 -0
- package/test/fixtures/home/.pi/agent/agents/same.md +6 -0
- package/test/fixtures/proj/.agents/agents/proj-shared.md +6 -0
- package/test/fixtures/proj/.pi/agents/project-pi.md +6 -0
- package/test/fixtures/proj/.pi/agents/same.md +6 -0
- package/test/helpers/fake-clock.mjs +39 -0
- package/test/helpers/feature-contracts.mjs +44 -0
- package/test/helpers/test-utils.mjs +44 -0
- package/test/verify-artifact-sessions.mjs +258 -0
- package/test/verify-backend.mjs +297 -0
- package/test/verify-child-mislabel.mjs +135 -0
- package/test/verify-child-surface.mjs +321 -0
- package/test/verify-cli.mjs +197 -0
- package/test/verify-command-ux.mjs +100 -0
- package/test/verify-compat.mjs +32 -0
- package/test/verify-cross-host-notes.mjs +128 -0
- package/test/verify-delegate.mjs +161 -0
- package/test/verify-detect.mjs +151 -0
- package/test/verify-discovery.mjs +239 -0
- package/test/verify-done-nudge.mjs +238 -0
- package/test/verify-effective-prompt.mjs +98 -0
- package/test/verify-hc-matrix.mjs +246 -0
- package/test/verify-hc-poll.mjs +260 -0
- package/test/verify-host-docs.mjs +66 -0
- package/test/verify-host-impact.mjs +49 -0
- package/test/verify-ids.mjs +141 -0
- package/test/verify-launch.mjs +183 -0
- package/test/verify-message-routing.mjs +560 -0
- package/test/verify-messaging.mjs +303 -0
- package/test/verify-migration-notice.mjs +74 -0
- package/test/verify-multi-wait.mjs +42 -0
- package/test/verify-opencode-display.mjs +47 -0
- package/test/verify-opencode-fieldnotes.mjs +121 -0
- package/test/verify-opencode-notice.mjs +77 -0
- package/test/verify-opencode-nudge.mjs +116 -0
- package/test/verify-opencode-orphans.mjs +160 -0
- package/test/verify-opencode-surface.mjs +107 -0
- package/test/verify-packaging.mjs +82 -0
- package/test/verify-parent-surface.mjs +118 -0
- package/test/verify-phase0.mjs +95 -0
- package/test/verify-registry.mjs +124 -0
- package/test/verify-rename-migration.mjs +111 -0
- package/test/verify-rendering.mjs +379 -0
- package/test/verify-session-boundary.mjs +146 -0
- package/test/verify-settings.mjs +260 -0
- package/test/verify-stale-wait.mjs +339 -0
- package/test/verify-status-widget.mjs +377 -0
- package/test/verify-status.mjs +172 -0
- package/test/verify-task-completion.mjs +156 -0
- package/test/verify-task-failures.mjs +201 -0
- package/test/verify-task-mislabel.mjs +143 -0
- package/test/verify-task-registry.mjs +194 -0
- package/test/verify-task-watchers.mjs +217 -0
- package/test/verify-tool-schemas.mjs +120 -0
- package/test/verify-unseen-completions.mjs +1211 -0
- package/test/verify-watchers.mjs +181 -0
|
@@ -0,0 +1,1211 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
/**
|
|
3
|
+
* Spec 007 verification: unseen-settlement ledger + unwatched-completion
|
|
4
|
+
* notice bridge.
|
|
5
|
+
*
|
|
6
|
+
* Core cases (task 1.3): ledger exclusions, dedupe, insertion order, drain and
|
|
7
|
+
* clear semantics, and the registry settlement observer. Bridge cases (task
|
|
8
|
+
* 3.1): session-scoped subscription, debounced idle wake, boundary
|
|
9
|
+
* continuation, retrieval/close clearing, renderer registration, and shutdown
|
|
10
|
+
* release. The bridge is driven directly through a fake pi surface (no pi
|
|
11
|
+
* subprocess), with an isolated ledger and injected coalesce windows.
|
|
12
|
+
*
|
|
13
|
+
* 010 Phase 2 adds the hc matrix alongside the 009 `verify-hc-matrix.mjs`
|
|
14
|
+
* pattern: same prompts on both runtimes settle to byte-identical notices
|
|
15
|
+
* modulo opaque ids, with no-id-leak, submission-failure, race, and close
|
|
16
|
+
* cases — deterministic (isolated ledgers, injected coalesce, fake pi).
|
|
17
|
+
*/
|
|
18
|
+
import assert from 'node:assert/strict';
|
|
19
|
+
import { chmodSync, mkdirSync, mkdtempSync, readFileSync, writeFileSync } from 'node:fs';
|
|
20
|
+
import { tmpdir } from 'node:os';
|
|
21
|
+
import * as path from 'node:path';
|
|
22
|
+
import { UnseenCompletionLedger, unseenCompletionLedger } from '../src/core/unseen-completions.ts';
|
|
23
|
+
import {
|
|
24
|
+
configureUnseenCompletionBridge,
|
|
25
|
+
formatUnseenCompletionNotice,
|
|
26
|
+
UNSEEN_NOTICE_COALESCE_MS,
|
|
27
|
+
UNSEEN_NOTICE_CUSTOM_TYPE,
|
|
28
|
+
} from '../src/extension/unseen-completions.ts';
|
|
29
|
+
import { doAction } from '../src/extension/shepherd.ts';
|
|
30
|
+
import { delegateAgent } from '../src/runtimes/herdr/lifecycle.ts';
|
|
31
|
+
import { LifecycleRegistry, lifecycleRegistry } from '../src/runtimes/herdr/orchestration.ts';
|
|
32
|
+
import {
|
|
33
|
+
isHcTaskId,
|
|
34
|
+
notifyHcTaskSettledObservers,
|
|
35
|
+
onTaskSettled as onHcTaskSettled,
|
|
36
|
+
resolveHcAgentId,
|
|
37
|
+
watchHcTasks,
|
|
38
|
+
} from '../src/runtimes/hc/runtime.ts';
|
|
39
|
+
|
|
40
|
+
const delay = ms => new Promise(resolve => setTimeout(resolve, ms));
|
|
41
|
+
|
|
42
|
+
// ── Ledger ──────────────────────────────────────────────────────────────
|
|
43
|
+
{
|
|
44
|
+
const ledger = new UnseenCompletionLedger();
|
|
45
|
+
const result = overrides => ({
|
|
46
|
+
taskId: 'shepherd-task-ledger-1',
|
|
47
|
+
agentId: 'shepherd-agent-ledger-1',
|
|
48
|
+
status: 'completed',
|
|
49
|
+
ok: true,
|
|
50
|
+
returnCode: 0,
|
|
51
|
+
text: 'done',
|
|
52
|
+
...overrides,
|
|
53
|
+
});
|
|
54
|
+
const context = overrides => ({
|
|
55
|
+
hadWatchers: false,
|
|
56
|
+
agent: 'worker',
|
|
57
|
+
label: 'ledger',
|
|
58
|
+
...overrides,
|
|
59
|
+
});
|
|
60
|
+
|
|
61
|
+
assert.equal(
|
|
62
|
+
ledger.record(
|
|
63
|
+
result({ taskId: 'shepherd-task-cancelled', status: 'cancelled', ok: false, returnCode: 130 }),
|
|
64
|
+
context()
|
|
65
|
+
),
|
|
66
|
+
false,
|
|
67
|
+
'cancelled settlements are excluded'
|
|
68
|
+
);
|
|
69
|
+
assert.equal(
|
|
70
|
+
ledger.record(result({ taskId: 'shepherd-task-watched' }), context({ hadWatchers: true })),
|
|
71
|
+
false,
|
|
72
|
+
'watched settlements are excluded'
|
|
73
|
+
);
|
|
74
|
+
assert.equal(
|
|
75
|
+
ledger.record(
|
|
76
|
+
result({ taskId: 'shepherd-task-failed-submit', status: 'failed', ok: false }),
|
|
77
|
+
context({ source: 'delegate-submission-failure' })
|
|
78
|
+
),
|
|
79
|
+
false,
|
|
80
|
+
'delegate submission failures are excluded'
|
|
81
|
+
);
|
|
82
|
+
assert.equal(ledger.pending().length, 0);
|
|
83
|
+
console.log('PASS ledger excludes cancelled, watched, and delegate-submission-failure settlements');
|
|
84
|
+
|
|
85
|
+
assert.equal(ledger.record(result(), context()), true, 'a first record adds an entry');
|
|
86
|
+
assert.deepEqual(
|
|
87
|
+
ledger.pending(),
|
|
88
|
+
[
|
|
89
|
+
{
|
|
90
|
+
taskId: 'shepherd-task-ledger-1',
|
|
91
|
+
agentId: 'shepherd-agent-ledger-1',
|
|
92
|
+
agent: 'worker',
|
|
93
|
+
label: 'ledger',
|
|
94
|
+
status: 'completed',
|
|
95
|
+
ok: true,
|
|
96
|
+
returnCode: 0,
|
|
97
|
+
text: 'done',
|
|
98
|
+
},
|
|
99
|
+
],
|
|
100
|
+
'record flattens result fields plus observer identity'
|
|
101
|
+
);
|
|
102
|
+
assert.equal(ledger.record(result(), context()), false, 'an existing entry is never replaced');
|
|
103
|
+
assert.equal(ledger.pending().length, 1);
|
|
104
|
+
const snapshot = ledger.pending();
|
|
105
|
+
snapshot[0].status = 'failed';
|
|
106
|
+
assert.equal(ledger.pending()[0].status, 'completed', 'pending() returns defensive copies');
|
|
107
|
+
console.log('PASS ledger flattens, dedupes by task id, and returns copies');
|
|
108
|
+
|
|
109
|
+
ledger.record(result({ taskId: 'shepherd-task-ledger-2' }), context({ label: '' }));
|
|
110
|
+
ledger.record(
|
|
111
|
+
result({ taskId: 'shepherd-task-other-agent' }),
|
|
112
|
+
context({ agent: 'reviewer', label: 'other' })
|
|
113
|
+
);
|
|
114
|
+
assert.deepEqual(
|
|
115
|
+
ledger.pending().map(settlement => settlement.taskId),
|
|
116
|
+
['shepherd-task-ledger-1', 'shepherd-task-ledger-2', 'shepherd-task-other-agent'],
|
|
117
|
+
'pending preserves insertion order'
|
|
118
|
+
);
|
|
119
|
+
ledger.drain(['shepherd-task-ledger-1', 'missing']);
|
|
120
|
+
assert.deepEqual(
|
|
121
|
+
ledger.pending().map(settlement => settlement.taskId),
|
|
122
|
+
['shepherd-task-ledger-2', 'shepherd-task-other-agent'],
|
|
123
|
+
'drain removes only present ids'
|
|
124
|
+
);
|
|
125
|
+
assert.deepEqual(
|
|
126
|
+
ledger.clear(['missing', 'shepherd-task-ledger-2']),
|
|
127
|
+
['shepherd-task-ledger-2'],
|
|
128
|
+
'clear returns removed ids in request order'
|
|
129
|
+
);
|
|
130
|
+
assert.deepEqual(
|
|
131
|
+
ledger.clearForAgent('shepherd-agent-ledger-1'),
|
|
132
|
+
['shepherd-task-other-agent'],
|
|
133
|
+
'clearForAgent returns the removed ids for that agent'
|
|
134
|
+
);
|
|
135
|
+
assert.equal(ledger.pending().length, 0);
|
|
136
|
+
ledger.record(result({ taskId: 'shepherd-task-ledger-3' }), context());
|
|
137
|
+
ledger.clearAll();
|
|
138
|
+
assert.equal(ledger.pending().length, 0);
|
|
139
|
+
console.log('PASS ledger supports insertion order, drain, clear, clearForAgent, and clearAll');
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
// ── Registry settlement observer ────────────────────────────────────────
|
|
143
|
+
{
|
|
144
|
+
const registry = new LifecycleRegistry();
|
|
145
|
+
const events = [];
|
|
146
|
+
const unsubscribe = registry.onTaskSettled((result, context) => {
|
|
147
|
+
events.push({ result, context });
|
|
148
|
+
});
|
|
149
|
+
|
|
150
|
+
const worker = registry.registerAgent({ agent: 'worker', label: 'observer-worker' });
|
|
151
|
+
const watchedTask = registry.createTask(worker, 'watched');
|
|
152
|
+
registry.setTaskRunning(watchedTask.id);
|
|
153
|
+
registry.watchTasks(watchedTask.id, () => {});
|
|
154
|
+
registry.settleTask(watchedTask.id, { status: 'completed', text: 'watched done' });
|
|
155
|
+
assert.equal(events.length, 1, 'one observation per settlement');
|
|
156
|
+
assert.equal(events[0].context.hadWatchers, true, 'a watcher callback marks hadWatchers');
|
|
157
|
+
assert.equal(events[0].result.status, 'completed');
|
|
158
|
+
events[0].result.status = 'failed';
|
|
159
|
+
assert.equal(
|
|
160
|
+
registry.taskResult(watchedTask.id).status,
|
|
161
|
+
'completed',
|
|
162
|
+
'the observer receives a shallow result copy'
|
|
163
|
+
);
|
|
164
|
+
console.log('PASS observer reports hadWatchers true for a watched settlement with a result copy');
|
|
165
|
+
|
|
166
|
+
const idleAgent = registry.registerAgent({ agent: 'scout', label: 'observer-idle' });
|
|
167
|
+
const unseenTask = registry.createTask(idleAgent, 'unseen');
|
|
168
|
+
registry.settleTask(unseenTask.id, { status: 'failed', error: 'nope' });
|
|
169
|
+
const unseenEvent = events.at(-1);
|
|
170
|
+
assert.equal(unseenEvent.context.hadWatchers, false);
|
|
171
|
+
assert.equal(unseenEvent.context.agent, 'scout');
|
|
172
|
+
assert.equal(unseenEvent.context.label, 'observer-idle');
|
|
173
|
+
assert.equal(unseenEvent.context.source, undefined);
|
|
174
|
+
assert.equal(unseenEvent.result.error, 'nope');
|
|
175
|
+
const eventCount = events.length;
|
|
176
|
+
registry.settleTask(unseenTask.id, { status: 'completed' });
|
|
177
|
+
assert.equal(events.length, eventCount, 'an already-settled task is not observed again');
|
|
178
|
+
console.log('PASS observer reports hadWatchers false with agent/label for an unwatched settlement');
|
|
179
|
+
|
|
180
|
+
const silentAgent = registry.registerAgent({ agent: 'worker', label: 'observer-silent' });
|
|
181
|
+
const silentTask = registry.createTask(silentAgent, 'silent');
|
|
182
|
+
registry.watchTasks(silentTask.id);
|
|
183
|
+
registry.settleTask(silentTask.id, { status: 'completed', text: 'silent done' });
|
|
184
|
+
assert.equal(
|
|
185
|
+
events.at(-1).context.hadWatchers,
|
|
186
|
+
false,
|
|
187
|
+
'a callback-less watcher registration does not count as observed'
|
|
188
|
+
);
|
|
189
|
+
console.log('PASS a callback-less watcher registration does not suppress the notice');
|
|
190
|
+
|
|
191
|
+
const sourceAgent = registry.registerAgent({ agent: 'worker', label: 'observer-source' });
|
|
192
|
+
const sourceTask = registry.createTask(sourceAgent, 'source');
|
|
193
|
+
registry.settleTask(
|
|
194
|
+
sourceTask.id,
|
|
195
|
+
{ status: 'failed', error: 'submit' },
|
|
196
|
+
{ source: 'delegate-submission-failure' }
|
|
197
|
+
);
|
|
198
|
+
assert.equal(
|
|
199
|
+
events.at(-1).context.source,
|
|
200
|
+
'delegate-submission-failure',
|
|
201
|
+
'the internal source tag reaches the observer'
|
|
202
|
+
);
|
|
203
|
+
console.log('PASS observer passes the delegate-submission-failure source tag through');
|
|
204
|
+
|
|
205
|
+
const offThrow = registry.onTaskSettled(() => {
|
|
206
|
+
throw new Error('observer boom');
|
|
207
|
+
});
|
|
208
|
+
const safeAgent = registry.registerAgent({ agent: 'worker', label: 'observer-safe' });
|
|
209
|
+
const safeTask = registry.createTask(safeAgent, 'safe');
|
|
210
|
+
const safeResult = registry.settleTask(safeTask.id, { status: 'completed', text: 'safe' });
|
|
211
|
+
assert.equal(safeResult.status, 'completed', 'a throwing observer cannot break settlement');
|
|
212
|
+
assert.equal(events.at(-1).result.taskId, safeTask.id, 'later observers still run');
|
|
213
|
+
offThrow();
|
|
214
|
+
console.log('PASS a throwing settlement observer cannot affect settlement');
|
|
215
|
+
|
|
216
|
+
const beforeUnsubscribe = events.length;
|
|
217
|
+
unsubscribe();
|
|
218
|
+
const afterAgent = registry.registerAgent({ agent: 'worker', label: 'observer-after' });
|
|
219
|
+
const afterTask = registry.createTask(afterAgent, 'after');
|
|
220
|
+
registry.settleTask(afterTask.id, { status: 'completed' });
|
|
221
|
+
assert.equal(events.length, beforeUnsubscribe, 'unsubscribe stops delivery');
|
|
222
|
+
console.log('PASS unsubscribe stops settlement observations');
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
// ── Notice formatter golden text ────────────────────────────────────────
|
|
226
|
+
{
|
|
227
|
+
const golden = formatUnseenCompletionNotice([
|
|
228
|
+
{
|
|
229
|
+
taskId: 'shepherd-task-alpha',
|
|
230
|
+
agentId: 'shepherd-agent-1',
|
|
231
|
+
agent: 'worker',
|
|
232
|
+
label: 'auth',
|
|
233
|
+
status: 'completed',
|
|
234
|
+
ok: true,
|
|
235
|
+
returnCode: 0,
|
|
236
|
+
text: 'implemented\nwith tests',
|
|
237
|
+
},
|
|
238
|
+
{
|
|
239
|
+
taskId: 'shepherd-task-beta',
|
|
240
|
+
agentId: 'shepherd-agent-2',
|
|
241
|
+
agent: 'reviewer',
|
|
242
|
+
status: 'failed',
|
|
243
|
+
ok: false,
|
|
244
|
+
returnCode: 1,
|
|
245
|
+
error: 'boom',
|
|
246
|
+
},
|
|
247
|
+
]);
|
|
248
|
+
assert.equal(
|
|
249
|
+
golden,
|
|
250
|
+
[
|
|
251
|
+
'Shepherd notice — 2 task(s) settled with no watcher attached:',
|
|
252
|
+
'- shepherd-task-alpha (worker "auth"): completed — implemented with tests',
|
|
253
|
+
'- shepherd-task-beta (reviewer): failed — boom',
|
|
254
|
+
'Full results: shepherd_watch({ id: [ "shepherd-task-alpha", "shepherd-task-beta" ] })',
|
|
255
|
+
].join('\n')
|
|
256
|
+
);
|
|
257
|
+
assert.equal(
|
|
258
|
+
formatUnseenCompletionNotice([
|
|
259
|
+
{
|
|
260
|
+
taskId: 'shepherd-task-solo',
|
|
261
|
+
agentId: 'shepherd-agent-solo',
|
|
262
|
+
status: 'timed_out',
|
|
263
|
+
ok: false,
|
|
264
|
+
returnCode: 124,
|
|
265
|
+
},
|
|
266
|
+
]),
|
|
267
|
+
[
|
|
268
|
+
'Shepherd notice — 1 task(s) settled with no watcher attached:',
|
|
269
|
+
'- shepherd-task-solo (shepherd-agent-solo): timed_out',
|
|
270
|
+
'Full results: shepherd_watch({ id: [ "shepherd-task-solo" ] })',
|
|
271
|
+
].join('\n')
|
|
272
|
+
);
|
|
273
|
+
assert.equal(UNSEEN_NOTICE_COALESCE_MS, 250, 'the production coalesce window stays 250ms');
|
|
274
|
+
assert.equal(
|
|
275
|
+
formatUnseenCompletionNotice([
|
|
276
|
+
{
|
|
277
|
+
taskId: 'shepherd-task-empty-text',
|
|
278
|
+
agentId: 'shepherd-agent-empty',
|
|
279
|
+
status: 'failed',
|
|
280
|
+
ok: false,
|
|
281
|
+
returnCode: 1,
|
|
282
|
+
text: '',
|
|
283
|
+
error: 'real error',
|
|
284
|
+
},
|
|
285
|
+
]).includes('failed — real error'),
|
|
286
|
+
true,
|
|
287
|
+
'an empty summary falls back to the error text'
|
|
288
|
+
);
|
|
289
|
+
const longSummary = 'x'.repeat(500);
|
|
290
|
+
const clipped = formatUnseenCompletionNotice([
|
|
291
|
+
{
|
|
292
|
+
taskId: 'shepherd-task-long',
|
|
293
|
+
agentId: 'shepherd-agent-long',
|
|
294
|
+
status: 'completed',
|
|
295
|
+
ok: true,
|
|
296
|
+
returnCode: 0,
|
|
297
|
+
text: longSummary,
|
|
298
|
+
},
|
|
299
|
+
]);
|
|
300
|
+
assert.ok(clipped.includes('…'), 'long summaries are clipped');
|
|
301
|
+
assert.ok(!clipped.includes(longSummary), 'the full summary is not inlined into the notice');
|
|
302
|
+
console.log('PASS the notice falls back to error text and clips long summaries');
|
|
303
|
+
console.log('PASS the notice formatter emits the spec 007 golden text');
|
|
304
|
+
}
|
|
305
|
+
|
|
306
|
+
// ── Parent bridge ───────────────────────────────────────────────────────
|
|
307
|
+
{
|
|
308
|
+
const sent = [];
|
|
309
|
+
const handlers = new Map();
|
|
310
|
+
let renderer;
|
|
311
|
+
const fakePi = {
|
|
312
|
+
registerMessageRenderer(customType, fn) {
|
|
313
|
+
renderer = { customType, fn };
|
|
314
|
+
},
|
|
315
|
+
on(event, handler) {
|
|
316
|
+
const list = handlers.get(event) ?? [];
|
|
317
|
+
list.push(handler);
|
|
318
|
+
handlers.set(event, list);
|
|
319
|
+
},
|
|
320
|
+
sendMessage(message, options) {
|
|
321
|
+
sent.push({ message, options });
|
|
322
|
+
},
|
|
323
|
+
};
|
|
324
|
+
const fire = async (event, payload, ctx) => {
|
|
325
|
+
const results = [];
|
|
326
|
+
for (const handler of handlers.get(event) ?? []) results.push(await handler(payload, ctx));
|
|
327
|
+
return results;
|
|
328
|
+
};
|
|
329
|
+
const idleFlag = { value: true };
|
|
330
|
+
const ctx = { isIdle: () => idleFlag.value };
|
|
331
|
+
const bridgeLedger = new UnseenCompletionLedger();
|
|
332
|
+
configureUnseenCompletionBridge(fakePi, { coalesceMs: 20, ledger: bridgeLedger });
|
|
333
|
+
|
|
334
|
+
assert.equal(renderer?.customType, UNSEEN_NOTICE_CUSTOM_TYPE);
|
|
335
|
+
assert.equal(typeof renderer?.fn, 'function');
|
|
336
|
+
console.log('PASS the bridge registers the shepherd.task.unseen renderer');
|
|
337
|
+
|
|
338
|
+
await fire('session_start', { type: 'session_start' }, ctx);
|
|
339
|
+
assert.deepEqual(
|
|
340
|
+
[...handlers.keys()].sort(),
|
|
341
|
+
['agent_before_settle', 'agent_settled', 'agent_start', 'session_shutdown', 'session_start'],
|
|
342
|
+
'the bridge subscribes to the lifecycle activity events'
|
|
343
|
+
);
|
|
344
|
+
console.log('PASS the bridge wires session, activity, boundary, and shutdown handlers');
|
|
345
|
+
|
|
346
|
+
// Idle burst: one coalesced wake, one drain, no duplicate.
|
|
347
|
+
const a1 = lifecycleRegistry.registerAgent({ agent: 'worker', label: 'bridge-idle-a' });
|
|
348
|
+
const t1 = lifecycleRegistry.createTask(a1, 'A');
|
|
349
|
+
lifecycleRegistry.settleTask(t1.id, { status: 'completed', text: 'done A' });
|
|
350
|
+
const a2 = lifecycleRegistry.registerAgent({ agent: 'reviewer', label: 'bridge-idle-b' });
|
|
351
|
+
const t2 = lifecycleRegistry.createTask(a2, 'B');
|
|
352
|
+
lifecycleRegistry.settleTask(t2.id, { status: 'failed', error: 'boom B' });
|
|
353
|
+
await delay(60);
|
|
354
|
+
assert.equal(sent.length, 1, 'an idle burst produces exactly one notice');
|
|
355
|
+
assert.equal(sent[0].message.customType, UNSEEN_NOTICE_CUSTOM_TYPE);
|
|
356
|
+
assert.equal(sent[0].message.display, true);
|
|
357
|
+
assert.deepEqual(sent[0].options, { triggerTurn: true });
|
|
358
|
+
assert.deepEqual(
|
|
359
|
+
sent[0].message.details.taskIds,
|
|
360
|
+
[t1.id, t2.id],
|
|
361
|
+
'the notice carries every coalesced task id'
|
|
362
|
+
);
|
|
363
|
+
assert.deepEqual(
|
|
364
|
+
sent[0].message.details.settlements.map(settlement => settlement.taskId),
|
|
365
|
+
[t1.id, t2.id]
|
|
366
|
+
);
|
|
367
|
+
assert.match(sent[0].message.content, /no watcher attached/);
|
|
368
|
+
assert.match(sent[0].message.content, /Full results: shepherd_watch\(\{ id: \[ /);
|
|
369
|
+
assert.equal(bridgeLedger.pending().length, 0, 'entries are drained after the idle send');
|
|
370
|
+
await delay(40);
|
|
371
|
+
assert.equal(sent.length, 1, 'no duplicate notice follows');
|
|
372
|
+
console.log('PASS an idle burst sends one coalesced triggerTurn notice and drains the ledger');
|
|
373
|
+
|
|
374
|
+
// A watched settlement never enters the ledger and never wakes the Shepherd.
|
|
375
|
+
const watchedAgent = lifecycleRegistry.registerAgent({ agent: 'worker', label: 'bridge-watched' });
|
|
376
|
+
const watchedTask = lifecycleRegistry.createTask(watchedAgent, 'watched');
|
|
377
|
+
lifecycleRegistry.watchTasks(watchedTask.id, () => {});
|
|
378
|
+
lifecycleRegistry.settleTask(watchedTask.id, { status: 'completed', text: 'watched done' });
|
|
379
|
+
await delay(40);
|
|
380
|
+
assert.equal(bridgeLedger.pending().length, 0, 'a watched settlement never enters the ledger');
|
|
381
|
+
assert.equal(sent.length, 1, 'a watched settlement produces no notice');
|
|
382
|
+
console.log('PASS a watched settlement is suppressed at the bridge level');
|
|
383
|
+
|
|
384
|
+
// Busy settlement: no mid-turn wake, delivery at the completed boundary once.
|
|
385
|
+
idleFlag.value = false;
|
|
386
|
+
await fire('agent_start', { type: 'agent_start' }, ctx);
|
|
387
|
+
const a3 = lifecycleRegistry.registerAgent({ agent: 'worker', label: 'bridge-busy-c' });
|
|
388
|
+
const t3 = lifecycleRegistry.createTask(a3, 'C');
|
|
389
|
+
lifecycleRegistry.settleTask(t3.id, { status: 'completed', text: 'done C' });
|
|
390
|
+
await delay(50);
|
|
391
|
+
assert.equal(sent.length, 1, 'no idle wake fires while the Shepherd is busy');
|
|
392
|
+
assert.equal(bridgeLedger.pending().length, 1);
|
|
393
|
+
|
|
394
|
+
// The completed-boundary fixtures below mirror pi's real pre-entry shape.
|
|
395
|
+
// `emitBoundary` (dist/core/extensions/runner.js) builds `event.context`
|
|
396
|
+
// from the entries accumulated BEFORE the handler runs; at a clean
|
|
397
|
+
// completed boundary that snapshot ends on the assistant's final turn, so
|
|
398
|
+
// `canContinue` is false even though the bridge's `custom_message` makes
|
|
399
|
+
// the run continuable.
|
|
400
|
+
// `_runBeforeSettleBoundary` (dist/core/agent-session.js) commits the
|
|
401
|
+
// returned drafts via `_commitBoundaryDrafts` and only then recomputes
|
|
402
|
+
// `finalContext.canContinue` via `_buildBoundaryContext`, where
|
|
403
|
+
// `canContinue = (hasNonSystemContext && finalRole !== 'assistant') ||
|
|
404
|
+
// pendingCustomContext || ...`. That post-commit gate is pi's and cannot be
|
|
405
|
+
// evaluated in this unit suite; it is covered by the real-pi probe, not
|
|
406
|
+
// here. Do not "fix" a fixture to `canContinue: true`: the pre-entry
|
|
407
|
+
// snapshot only reaches true when queued or pending messages already exist
|
|
408
|
+
// (agent-session.js:630-632), which is not the case this bridge handles
|
|
409
|
+
// (see #16/#17).
|
|
410
|
+
const boundaryEvent = {
|
|
411
|
+
type: 'agent_before_settle',
|
|
412
|
+
outcome: 'completed',
|
|
413
|
+
// The pre-entry snapshot is non-continuable at a clean completed
|
|
414
|
+
// boundary, so the bridge must still deliver.
|
|
415
|
+
context: { canContinue: false },
|
|
416
|
+
};
|
|
417
|
+
const boundary = (await fire('agent_before_settle', boundaryEvent, ctx))[0];
|
|
418
|
+
assert.ok(boundary, 'a completed boundary offers a continuation');
|
|
419
|
+
assert.equal(boundary.continue, true, 'a completed boundary continues once');
|
|
420
|
+
assert.equal(boundary.entries.length, 1);
|
|
421
|
+
const entry = boundary.entries[0];
|
|
422
|
+
assert.equal(entry.type, 'custom_message');
|
|
423
|
+
assert.equal(entry.customType, UNSEEN_NOTICE_CUSTOM_TYPE);
|
|
424
|
+
assert.equal(entry.display, true);
|
|
425
|
+
assert.deepEqual(entry.details.taskIds, [t3.id]);
|
|
426
|
+
assert.equal(entry.details.settlements.length, 1);
|
|
427
|
+
assert.ok(Array.isArray(entry.details.settlements));
|
|
428
|
+
assert.equal(bridgeLedger.pending().length, 0, 'the boundary drains the entries it delivered');
|
|
429
|
+
assert.equal(
|
|
430
|
+
(await fire('agent_before_settle', boundaryEvent, ctx))[0],
|
|
431
|
+
undefined,
|
|
432
|
+
'a second boundary without new entries does not continue'
|
|
433
|
+
);
|
|
434
|
+
console.log('PASS a busy settlement is delivered once at the completed settle boundary');
|
|
435
|
+
|
|
436
|
+
// A non-continuable pre-entry snapshot never suppresses a completed
|
|
437
|
+
// boundary: the bridge offers the continuation, drains its entries, and
|
|
438
|
+
// leaves the post-commit decision to pi.
|
|
439
|
+
const a4b = lifecycleRegistry.registerAgent({ agent: 'worker', label: 'bridge-busy-d2' });
|
|
440
|
+
const t4b = lifecycleRegistry.createTask(a4b, 'D2');
|
|
441
|
+
lifecycleRegistry.settleTask(t4b.id, { status: 'completed', text: 'done D2' });
|
|
442
|
+
const continuation = (
|
|
443
|
+
await fire(
|
|
444
|
+
'agent_before_settle',
|
|
445
|
+
{ type: 'agent_before_settle', outcome: 'completed', context: { canContinue: false } },
|
|
446
|
+
ctx
|
|
447
|
+
)
|
|
448
|
+
)[0];
|
|
449
|
+
assert.ok(
|
|
450
|
+
continuation,
|
|
451
|
+
'a completed boundary with canContinue false still offers a continuation'
|
|
452
|
+
);
|
|
453
|
+
assert.equal(
|
|
454
|
+
continuation.continue,
|
|
455
|
+
true,
|
|
456
|
+
'a completed boundary always offers the continuation'
|
|
457
|
+
);
|
|
458
|
+
assert.equal(continuation.entries.length, 1);
|
|
459
|
+
assert.equal(continuation.entries[0].type, 'custom_message');
|
|
460
|
+
assert.deepEqual(continuation.entries[0].details.taskIds, [t4b.id]);
|
|
461
|
+
assert.equal(ledgerCount(bridgeLedger), 0, 'the delivered entries are drained');
|
|
462
|
+
assert.equal(sent.length, 1, 'the boundary delivers in-turn instead of via sendMessage');
|
|
463
|
+
console.log('PASS a completed boundary with canContinue false still continues');
|
|
464
|
+
|
|
465
|
+
// The aborted outcome returns before the context is consulted, so this
|
|
466
|
+
// fixture's `canContinue` value is irrelevant; it only pins that an aborted
|
|
467
|
+
// boundary never continues.
|
|
468
|
+
const a4 = lifecycleRegistry.registerAgent({ agent: 'worker', label: 'bridge-busy-d' });
|
|
469
|
+
const t4 = lifecycleRegistry.createTask(a4, 'D');
|
|
470
|
+
lifecycleRegistry.settleTask(t4.id, { status: 'completed', text: 'done D' });
|
|
471
|
+
assert.equal(
|
|
472
|
+
(
|
|
473
|
+
await fire(
|
|
474
|
+
'agent_before_settle',
|
|
475
|
+
{ type: 'agent_before_settle', outcome: 'aborted', context: { canContinue: true } },
|
|
476
|
+
ctx
|
|
477
|
+
)
|
|
478
|
+
)[0],
|
|
479
|
+
undefined,
|
|
480
|
+
'an aborted run never continues'
|
|
481
|
+
);
|
|
482
|
+
assert.equal(ledgerCount(bridgeLedger), 1);
|
|
483
|
+
idleFlag.value = true;
|
|
484
|
+
await fire('agent_settled', { type: 'agent_settled' }, ctx);
|
|
485
|
+
await delay(60);
|
|
486
|
+
assert.equal(sent.length, 2, 'the agent_settled transition wakes the pending batch once');
|
|
487
|
+
assert.deepEqual(sent[1].message.details.taskIds, [t4.id]);
|
|
488
|
+
assert.equal(bridgeLedger.pending().length, 0);
|
|
489
|
+
console.log('PASS an aborted boundary leaves entries pending for one idle wake');
|
|
490
|
+
|
|
491
|
+
// Session shutdown releases the observer subscription and clears state.
|
|
492
|
+
await fire('session_shutdown', { type: 'session_shutdown' }, ctx);
|
|
493
|
+
const a7 = lifecycleRegistry.registerAgent({ agent: 'worker', label: 'bridge-shutdown-g' });
|
|
494
|
+
const t7 = lifecycleRegistry.createTask(a7, 'G');
|
|
495
|
+
lifecycleRegistry.settleTask(t7.id, { status: 'completed', text: 'after shutdown' });
|
|
496
|
+
await delay(60);
|
|
497
|
+
assert.equal(bridgeLedger.pending().length, 0, 'no recording after shutdown');
|
|
498
|
+
assert.equal(sent.length, 2, 'no notice after shutdown');
|
|
499
|
+
console.log('PASS session_shutdown releases the settlement subscription and clears state');
|
|
500
|
+
}
|
|
501
|
+
|
|
502
|
+
// ── Retrieval/close clearing (production singleton wiring) ─────────────
|
|
503
|
+
{
|
|
504
|
+
const sent = [];
|
|
505
|
+
const handlers = new Map();
|
|
506
|
+
const fakePi = {
|
|
507
|
+
registerMessageRenderer() {},
|
|
508
|
+
on(event, handler) {
|
|
509
|
+
handlers.set(event, handler);
|
|
510
|
+
},
|
|
511
|
+
sendMessage(message, options) {
|
|
512
|
+
sent.push({ message, options });
|
|
513
|
+
},
|
|
514
|
+
};
|
|
515
|
+
const fire = async (event, payload, ctx) => handlers.get(event)?.(payload, ctx);
|
|
516
|
+
configureUnseenCompletionBridge(fakePi, { coalesceMs: 20 });
|
|
517
|
+
await fire('session_start', { type: 'session_start' }, { isIdle: () => false });
|
|
518
|
+
assert.equal(unseenCompletionLedger.pending().length, 0);
|
|
519
|
+
|
|
520
|
+
// Late explicit watch is the authoritative retrieval clear.
|
|
521
|
+
await fire('agent_start', { type: 'agent_start' }, { isIdle: () => false });
|
|
522
|
+
const a5 = lifecycleRegistry.registerAgent({ agent: 'worker', label: 'bridge-watch-e' });
|
|
523
|
+
const t5 = lifecycleRegistry.createTask(a5, 'E');
|
|
524
|
+
lifecycleRegistry.settleTask(t5.id, { status: 'completed', text: 'done E' });
|
|
525
|
+
assert.equal(ledgerCount(unseenCompletionLedger), 1);
|
|
526
|
+
// Phase 2: `shepherd_watch` routes through the resolved runtime. Pin the
|
|
527
|
+
// sandbox user layer to the pane backend so this herdr-task watch keeps
|
|
528
|
+
// proving pane behavior deterministically (same precedent as the close
|
|
529
|
+
// test below: an explicit pin wins over caller detection). A pinned
|
|
530
|
+
// backend must be reachable, so a fake `herdr` answers on a sandbox PATH.
|
|
531
|
+
const previousWatchAgentDir = process.env.PI_CODING_AGENT_DIR;
|
|
532
|
+
const previousWatchPath = process.env.PATH;
|
|
533
|
+
const watchSandbox = mkdtempSync(path.join(tmpdir(), 'pi-shepherd-unseen-watch-'));
|
|
534
|
+
mkdirSync(path.join(watchSandbox, 'pi-shepherd'), { recursive: true });
|
|
535
|
+
mkdirSync(path.join(watchSandbox, 'bin'), { recursive: true });
|
|
536
|
+
writeFileSync(
|
|
537
|
+
path.join(watchSandbox, 'pi-shepherd', 'config.json'),
|
|
538
|
+
JSON.stringify({ backend: 'herdr' })
|
|
539
|
+
);
|
|
540
|
+
writeFileSync(
|
|
541
|
+
path.join(watchSandbox, 'bin', 'herdr'),
|
|
542
|
+
'#!/bin/sh\ncase "$1 $2" in\n "status server") printf \'status: running\\n\' ;;\n *) printf \'%s\\n\' \'{\"result\":{}}\' ;;\nesac\nexit 0\n'
|
|
543
|
+
);
|
|
544
|
+
chmodSync(path.join(watchSandbox, 'bin', 'herdr'), 0o755);
|
|
545
|
+
process.env.PI_CODING_AGENT_DIR = watchSandbox;
|
|
546
|
+
process.env.PATH = `${path.join(watchSandbox, 'bin')}${path.delimiter}${previousWatchPath ?? ''}`;
|
|
547
|
+
try {
|
|
548
|
+
await doAction({ action: 'watch', id: t5.id }, { cwd: process.cwd() });
|
|
549
|
+
} finally {
|
|
550
|
+
if (previousWatchAgentDir === undefined) delete process.env.PI_CODING_AGENT_DIR;
|
|
551
|
+
else process.env.PI_CODING_AGENT_DIR = previousWatchAgentDir;
|
|
552
|
+
if (previousWatchPath === undefined) delete process.env.PATH;
|
|
553
|
+
else process.env.PATH = previousWatchPath;
|
|
554
|
+
}
|
|
555
|
+
assert.equal(
|
|
556
|
+
unseenCompletionLedger.pending().length,
|
|
557
|
+
0,
|
|
558
|
+
'an explicit watch clears the pending entry'
|
|
559
|
+
);
|
|
560
|
+
await delay(40);
|
|
561
|
+
assert.equal(sent.length, 0, 'no notice follows a retrieval clear');
|
|
562
|
+
console.log('PASS shepherd_watch retrieval clears the pending unseen settlement');
|
|
563
|
+
|
|
564
|
+
// Close drops an agent's pending entries and reports them in the result.
|
|
565
|
+
const sandbox = mkdtempSync(path.join(tmpdir(), 'pi-shepherd-unseen-'));
|
|
566
|
+
const agentDir = path.join(sandbox, 'agent');
|
|
567
|
+
const binDir = path.join(sandbox, 'bin');
|
|
568
|
+
mkdirSync(path.join(agentDir, 'pi-shepherd'), { recursive: true });
|
|
569
|
+
mkdirSync(binDir, { recursive: true });
|
|
570
|
+
const paneId = 'pane-unseen-close';
|
|
571
|
+
writeFileSync(
|
|
572
|
+
path.join(agentDir, 'pi-shepherd', 'created-panes.json'),
|
|
573
|
+
JSON.stringify([
|
|
574
|
+
{ paneId, tabId: 'tab-unseen-close', name: 'worker', cwd: process.cwd(), createdAt: Date.now() },
|
|
575
|
+
])
|
|
576
|
+
);
|
|
577
|
+
const fakeHerdr = path.join(binDir, 'herdr');
|
|
578
|
+
writeFileSync(
|
|
579
|
+
fakeHerdr,
|
|
580
|
+
`#!/bin/sh
|
|
581
|
+
case "$1 $2" in
|
|
582
|
+
"agent get") printf '{"result":{"agent":{"pane_id":"%s","agent_status":"idle"}}}\\n' "$3" ;;
|
|
583
|
+
"pane list") printf '%s\\n' '{"result":{"panes":[]}}' ;;
|
|
584
|
+
"status server") printf 'status: running\\n' ;;
|
|
585
|
+
*) printf '%s\\n' '{"result":{}}' ;;
|
|
586
|
+
esac
|
|
587
|
+
exit 0
|
|
588
|
+
`
|
|
589
|
+
);
|
|
590
|
+
chmodSync(fakeHerdr, 0o755);
|
|
591
|
+
const previousPath = process.env.PATH;
|
|
592
|
+
const previousAgentDir = process.env.PI_CODING_AGENT_DIR;
|
|
593
|
+
process.env.PATH = `${binDir}${path.delimiter}${previousPath ?? ''}`;
|
|
594
|
+
process.env.PI_CODING_AGENT_DIR = agentDir;
|
|
595
|
+
// Phase 1.2: doAction close routes through the resolved runtime. Pin the
|
|
596
|
+
// sandbox user layer to the pane backend so this fake-herdr world keeps
|
|
597
|
+
// proving pane-close behavior deterministically (the fake answers
|
|
598
|
+
// --version and a running `status server`, so the pin resolves). This
|
|
599
|
+
// doubles as the e2e proof that an explicit backend pin wins over
|
|
600
|
+
// caller detection.
|
|
601
|
+
writeFileSync(
|
|
602
|
+
path.join(agentDir, 'pi-shepherd', 'config.json'),
|
|
603
|
+
JSON.stringify({ backend: 'herdr' })
|
|
604
|
+
);
|
|
605
|
+
try {
|
|
606
|
+
const a6 = lifecycleRegistry.registerAgent({ agent: 'worker', label: 'bridge-close-f', paneId });
|
|
607
|
+
const t6 = lifecycleRegistry.createTask(a6, 'F');
|
|
608
|
+
lifecycleRegistry.settleTask(t6.id, { status: 'completed', text: 'done F' });
|
|
609
|
+
assert.equal(ledgerCount(unseenCompletionLedger), 1);
|
|
610
|
+
const closeResult = await doAction({ action: 'close', id: a6.id }, { cwd: process.cwd() });
|
|
611
|
+
const closeText = closeResult.content[0].text;
|
|
612
|
+
assert.match(closeText, /cleared 1 unseen completion\(s\)/);
|
|
613
|
+
assert.ok(closeText.includes(t6.id), 'the close summary names the dropped task id');
|
|
614
|
+
assert.deepEqual(closeResult.details.clearedUnseenCompletions, [t6.id]);
|
|
615
|
+
assert.equal(
|
|
616
|
+
unseenCompletionLedger.pending().length,
|
|
617
|
+
0,
|
|
618
|
+
'close clears the agent pending entries'
|
|
619
|
+
);
|
|
620
|
+
await delay(40);
|
|
621
|
+
assert.equal(sent.length, 0, 'no notice is sent for entries dropped by close');
|
|
622
|
+
console.log('PASS shepherd_close clears and reports the dropped unseen completions');
|
|
623
|
+
|
|
624
|
+
// A delegate submission failure settles the task but must never enter the
|
|
625
|
+
// ledger: the Shepherd already sees the error in the shepherd_delegate
|
|
626
|
+
// tool result. This guards the source tag wired in lifecycle.ts.
|
|
627
|
+
const observed = [];
|
|
628
|
+
const offObserved = lifecycleRegistry.onTaskSettled((_result, context) => {
|
|
629
|
+
observed.push(context);
|
|
630
|
+
});
|
|
631
|
+
const failedAgent = lifecycleRegistry.registerAgent({
|
|
632
|
+
agent: 'worker',
|
|
633
|
+
label: 'bridge-delegate-fail',
|
|
634
|
+
paneId: 'pane-unseen-delegate-fail',
|
|
635
|
+
});
|
|
636
|
+
const notADirectory = path.join(sandbox, 'not-a-directory');
|
|
637
|
+
writeFileSync(notADirectory, 'this is a file, not a session directory');
|
|
638
|
+
await assert.rejects(
|
|
639
|
+
() =>
|
|
640
|
+
delegateAgent(failedAgent, 'fails during artifact reservation', {
|
|
641
|
+
sessionId: 'unseen-delegate-failure',
|
|
642
|
+
artifactSession: {
|
|
643
|
+
sessionName: 'broken',
|
|
644
|
+
slug: 'broken',
|
|
645
|
+
ordinal: 1,
|
|
646
|
+
directoryName: 'broken',
|
|
647
|
+
projectRoot: sandbox,
|
|
648
|
+
sessionPath: notADirectory,
|
|
649
|
+
sessionRelativePath: 'broken',
|
|
650
|
+
mocPath: path.join(sandbox, 'broken.md'),
|
|
651
|
+
sessionMetadataPath: path.join(sandbox, 'broken.json'),
|
|
652
|
+
resumed: false,
|
|
653
|
+
startedAt: new Date().toISOString(),
|
|
654
|
+
updatedAt: new Date().toISOString(),
|
|
655
|
+
status: 'running',
|
|
656
|
+
},
|
|
657
|
+
}),
|
|
658
|
+
/Task submission failed/
|
|
659
|
+
);
|
|
660
|
+
offObserved();
|
|
661
|
+
assert.equal(
|
|
662
|
+
observed.at(-1)?.source,
|
|
663
|
+
'delegate-submission-failure',
|
|
664
|
+
'the real delegate failure path tags its settlement'
|
|
665
|
+
);
|
|
666
|
+
assert.equal(
|
|
667
|
+
unseenCompletionLedger.pending().length,
|
|
668
|
+
0,
|
|
669
|
+
'a delegate submission failure never records an unseen completion'
|
|
670
|
+
);
|
|
671
|
+
console.log('PASS delegate submission failures are excluded end-to-end');
|
|
672
|
+
} finally {
|
|
673
|
+
if (previousPath === undefined) delete process.env.PATH;
|
|
674
|
+
else process.env.PATH = previousPath;
|
|
675
|
+
if (previousAgentDir === undefined) delete process.env.PI_CODING_AGENT_DIR;
|
|
676
|
+
else process.env.PI_CODING_AGENT_DIR = previousAgentDir;
|
|
677
|
+
}
|
|
678
|
+
|
|
679
|
+
await fire('session_shutdown', { type: 'session_shutdown' }, { isIdle: () => true });
|
|
680
|
+
assert.equal(unseenCompletionLedger.pending().length, 0);
|
|
681
|
+
}
|
|
682
|
+
|
|
683
|
+
// ── Fake pi without sendMessage ─────────────────────────────────────────
|
|
684
|
+
{
|
|
685
|
+
const handlers2 = new Map();
|
|
686
|
+
const fakePi2 = {
|
|
687
|
+
registerMessageRenderer() {},
|
|
688
|
+
on(event, handler) {
|
|
689
|
+
handlers2.set(event, handler);
|
|
690
|
+
},
|
|
691
|
+
};
|
|
692
|
+
const fire2 = async (event, payload, ctx2) => handlers2.get(event)?.(payload, ctx2);
|
|
693
|
+
const ledger2 = new UnseenCompletionLedger();
|
|
694
|
+
configureUnseenCompletionBridge(fakePi2, { coalesceMs: 10, ledger: ledger2 });
|
|
695
|
+
await fire2('session_start', { type: 'session_start' }, { isIdle: () => true });
|
|
696
|
+
const a8 = lifecycleRegistry.registerAgent({ agent: 'worker', label: 'bridge-nosend-h' });
|
|
697
|
+
const t8 = lifecycleRegistry.createTask(a8, 'H');
|
|
698
|
+
lifecycleRegistry.settleTask(t8.id, { status: 'completed', text: 'no send' });
|
|
699
|
+
await delay(40);
|
|
700
|
+
assert.equal(
|
|
701
|
+
ledger2.pending().length,
|
|
702
|
+
1,
|
|
703
|
+
'a pi without sendMessage leaves entries pending without throwing'
|
|
704
|
+
);
|
|
705
|
+
await fire2('session_shutdown', { type: 'session_shutdown' });
|
|
706
|
+
assert.equal(ledger2.pending().length, 0);
|
|
707
|
+
console.log('PASS a fake pi without sendMessage never throws and keeps entries pending');
|
|
708
|
+
}
|
|
709
|
+
|
|
710
|
+
// ── hc matrix (010 Phase 2; cross-links test/verify-hc-matrix.mjs) ───────
|
|
711
|
+
// Same prompts on both runtimes settle through one bridge seam: Herdr via a
|
|
712
|
+
// registry observer, hc via `notifyHcTaskSettledObservers` (the settle-path
|
|
713
|
+
// call Phase 0 exports so observer parity is unit-testable without a live
|
|
714
|
+
// terminal). Deterministic: isolated ledgers, injected coalesce windows,
|
|
715
|
+
// fake pi surface, no live spawn — the same discipline as the bridge cases
|
|
716
|
+
// above and the 009 `verify-hc-matrix.mjs` pattern.
|
|
717
|
+
{
|
|
718
|
+
const PROMPT = 'Implement the auth middleware from the plan.';
|
|
719
|
+
const SUMMARY = 'implemented with tests';
|
|
720
|
+
const normalizeIds = text =>
|
|
721
|
+
text.replace(/shepherd-(task|agent)-[A-Za-z0-9-]+/g, 'shepherd-$1-<id>');
|
|
722
|
+
|
|
723
|
+
// Same prompts, both runtimes: byte-identical notice text modulo ids.
|
|
724
|
+
const herdrLedger = new UnseenCompletionLedger();
|
|
725
|
+
const herdrMatrix = new LifecycleRegistry();
|
|
726
|
+
const herdrOff = herdrMatrix.onTaskSettled((result, context) => {
|
|
727
|
+
herdrLedger.record(result, context);
|
|
728
|
+
});
|
|
729
|
+
const herdrAgent = herdrMatrix.registerAgent({ agent: 'worker', label: 'matrix' });
|
|
730
|
+
const herdrTask = herdrMatrix.createTask(herdrAgent, PROMPT);
|
|
731
|
+
herdrMatrix.setTaskRunning(herdrTask.id);
|
|
732
|
+
herdrMatrix.settleTask(herdrTask.id, { status: 'completed', text: SUMMARY });
|
|
733
|
+
herdrOff();
|
|
734
|
+
assert.equal(herdrLedger.pending().length, 1, 'herdr settle records one unseen entry');
|
|
735
|
+
|
|
736
|
+
const hcLedger = new UnseenCompletionLedger();
|
|
737
|
+
const hcAgentId = 'shepherd-agent-hc-matrix-0001';
|
|
738
|
+
const hcTaskId = 'shepherd-task-hc-matrix-0001';
|
|
739
|
+
const hcOff = onHcTaskSettled((result, context) => {
|
|
740
|
+
hcLedger.record(result, context);
|
|
741
|
+
});
|
|
742
|
+
notifyHcTaskSettledObservers(
|
|
743
|
+
{
|
|
744
|
+
taskId: hcTaskId,
|
|
745
|
+
agentId: hcAgentId,
|
|
746
|
+
status: 'completed',
|
|
747
|
+
ok: true,
|
|
748
|
+
returnCode: 0,
|
|
749
|
+
text: SUMMARY,
|
|
750
|
+
completedAt: Date.now(),
|
|
751
|
+
},
|
|
752
|
+
{ hadWatchers: false, agent: 'worker', label: 'matrix' }
|
|
753
|
+
);
|
|
754
|
+
hcOff();
|
|
755
|
+
assert.equal(hcLedger.pending().length, 1, 'hc observation records one unseen entry');
|
|
756
|
+
assert.equal(
|
|
757
|
+
normalizeIds(formatUnseenCompletionNotice(hcLedger.pending())),
|
|
758
|
+
normalizeIds(formatUnseenCompletionNotice(herdrLedger.pending())),
|
|
759
|
+
'same prompts settle to byte-identical notices modulo opaque ids'
|
|
760
|
+
);
|
|
761
|
+
console.log('PASS same prompts on both runtimes settle to byte-identical notices modulo ids');
|
|
762
|
+
|
|
763
|
+
// No id leak on hc: notices, details, and tool refusals carry opaque ids
|
|
764
|
+
// only — no raw terminal/pane addresses, socket paths, or env values.
|
|
765
|
+
const hcNoticeJson = JSON.stringify({
|
|
766
|
+
content: formatUnseenCompletionNotice(hcLedger.pending()),
|
|
767
|
+
details: hcLedger.pending(),
|
|
768
|
+
});
|
|
769
|
+
for (const [pattern, name] of [
|
|
770
|
+
[/\bw\d+:p\d+\b/, 'pane id'],
|
|
771
|
+
[/(?:^|\W)t\d+(?:\W|$)/, 'terminal address'],
|
|
772
|
+
[/\.sock\b/, 'socket path'],
|
|
773
|
+
[/HERDR_/, 'HERDR_* value'],
|
|
774
|
+
[/\bHC_/, 'HC_* value'],
|
|
775
|
+
]) {
|
|
776
|
+
assert.ok(!pattern.test(hcNoticeJson), `hc notice carries no ${name}`);
|
|
777
|
+
}
|
|
778
|
+
assert.ok(hcNoticeJson.includes(hcTaskId), 'hc notice names the opaque task id');
|
|
779
|
+
assert.equal(isHcTaskId('t4'), false, 'isHcTaskId refuses a raw terminal address');
|
|
780
|
+
assert.equal(isHcTaskId('w1:p1'), false, 'isHcTaskId refuses a raw pane id');
|
|
781
|
+
assert.equal(resolveHcAgentId('t4'), undefined, 'read-target resolution refuses raw terminals');
|
|
782
|
+
assert.equal(resolveHcAgentId('w1:p1'), undefined, 'read-target resolution refuses raw panes');
|
|
783
|
+
assert.throws(() => watchHcTasks('t4'), /Unknown task/, 'hc watch refuses a raw address');
|
|
784
|
+
let rawRefusal = '';
|
|
785
|
+
try {
|
|
786
|
+
watchHcTasks('t4');
|
|
787
|
+
} catch (error) {
|
|
788
|
+
rawRefusal = String(error?.message ?? error);
|
|
789
|
+
}
|
|
790
|
+
assert.ok(!/\.sock/.test(rawRefusal) && !/HERDR_|HC_/.test(rawRefusal));
|
|
791
|
+
console.log('PASS hc notices, details, and tool refusals leak no native ids');
|
|
792
|
+
|
|
793
|
+
// delegate-submission-failure on hc records nothing.
|
|
794
|
+
const failureLedger = new UnseenCompletionLedger();
|
|
795
|
+
const failureOff = onHcTaskSettled((result, context) => {
|
|
796
|
+
failureLedger.record(result, context);
|
|
797
|
+
});
|
|
798
|
+
notifyHcTaskSettledObservers(
|
|
799
|
+
{
|
|
800
|
+
taskId: 'shepherd-task-hc-matrix-failure',
|
|
801
|
+
agentId: hcAgentId,
|
|
802
|
+
status: 'failed',
|
|
803
|
+
ok: false,
|
|
804
|
+
returnCode: 1,
|
|
805
|
+
error: 'submit boom',
|
|
806
|
+
completedAt: Date.now(),
|
|
807
|
+
},
|
|
808
|
+
{
|
|
809
|
+
hadWatchers: false,
|
|
810
|
+
agent: 'worker',
|
|
811
|
+
label: 'matrix',
|
|
812
|
+
source: 'delegate-submission-failure',
|
|
813
|
+
}
|
|
814
|
+
);
|
|
815
|
+
failureOff();
|
|
816
|
+
assert.equal(failureLedger.pending().length, 0, 'an hc submission failure records nothing');
|
|
817
|
+
console.log('PASS delegate-submission-failure on hc records nothing');
|
|
818
|
+
|
|
819
|
+
// Timeout-vs-done race: the first settlement wins, the loser is ignored,
|
|
820
|
+
// and the winner stays readable for shepherd_watch/shepherd_read.
|
|
821
|
+
const raceRegistry = new LifecycleRegistry();
|
|
822
|
+
const raceEvents = [];
|
|
823
|
+
const raceOff = raceRegistry.onTaskSettled((result, context) => {
|
|
824
|
+
raceEvents.push({ result, context });
|
|
825
|
+
});
|
|
826
|
+
const raceAgent = raceRegistry.registerAgent({ agent: 'worker', label: 'race' });
|
|
827
|
+
const raceTask = raceRegistry.createTask(raceAgent, PROMPT);
|
|
828
|
+
raceRegistry.setTaskRunning(raceTask.id);
|
|
829
|
+
raceRegistry.settleTask(raceTask.id, {
|
|
830
|
+
status: 'timed_out',
|
|
831
|
+
error: 'Tracked task deadline reached.',
|
|
832
|
+
});
|
|
833
|
+
const lateLoser = raceRegistry.settleTask(raceTask.id, {
|
|
834
|
+
status: 'completed',
|
|
835
|
+
text: 'late done',
|
|
836
|
+
});
|
|
837
|
+
assert.equal(lateLoser.status, 'timed_out', 'a late done cannot overwrite the deadline');
|
|
838
|
+
assert.equal(raceEvents.length, 1, 'the loser is never observed');
|
|
839
|
+
assert.equal(raceRegistry.taskResult(raceTask.id).status, 'timed_out');
|
|
840
|
+
assert.equal(raceRegistry.taskResult(raceTask.id).error, 'Tracked task deadline reached.');
|
|
841
|
+
raceOff();
|
|
842
|
+
const raceLedger = new UnseenCompletionLedger();
|
|
843
|
+
const raceHcOff = onHcTaskSettled((result, context) => {
|
|
844
|
+
raceLedger.record(result, context);
|
|
845
|
+
});
|
|
846
|
+
const raceTaskId = 'shepherd-task-hc-matrix-race';
|
|
847
|
+
notifyHcTaskSettledObservers(
|
|
848
|
+
{
|
|
849
|
+
taskId: raceTaskId,
|
|
850
|
+
agentId: hcAgentId,
|
|
851
|
+
status: 'timed_out',
|
|
852
|
+
ok: false,
|
|
853
|
+
returnCode: 124,
|
|
854
|
+
text: 'Timed out waiting for a reply from the target agent (message never answered).',
|
|
855
|
+
error: 'Tracked reply deadline reached.',
|
|
856
|
+
completedAt: Date.now(),
|
|
857
|
+
},
|
|
858
|
+
{ hadWatchers: false, agent: 'worker', label: 'race' }
|
|
859
|
+
);
|
|
860
|
+
notifyHcTaskSettledObservers(
|
|
861
|
+
{
|
|
862
|
+
taskId: raceTaskId,
|
|
863
|
+
agentId: hcAgentId,
|
|
864
|
+
status: 'completed',
|
|
865
|
+
ok: true,
|
|
866
|
+
returnCode: 0,
|
|
867
|
+
text: 'late done',
|
|
868
|
+
completedAt: Date.now(),
|
|
869
|
+
},
|
|
870
|
+
{ hadWatchers: false, agent: 'worker', label: 'race' }
|
|
871
|
+
);
|
|
872
|
+
raceHcOff();
|
|
873
|
+
assert.equal(raceLedger.pending().length, 1, 'single winner-only unseen entry');
|
|
874
|
+
assert.equal(raceLedger.pending()[0].status, 'timed_out', 'the deadline winner is kept');
|
|
875
|
+
assert.ok(raceLedger.pending()[0].text.includes('Timed out waiting'));
|
|
876
|
+
const hcRuntimeSource = readFileSync(
|
|
877
|
+
new URL('../src/runtimes/hc/runtime.ts', import.meta.url),
|
|
878
|
+
'utf8'
|
|
879
|
+
);
|
|
880
|
+
const paneRegistrySource = readFileSync(
|
|
881
|
+
new URL('../src/runtimes/herdr/orchestration.ts', import.meta.url),
|
|
882
|
+
'utf8'
|
|
883
|
+
);
|
|
884
|
+
assert.ok(
|
|
885
|
+
hcRuntimeSource.includes('if (record.result) return'),
|
|
886
|
+
'hc second settle is a no-op'
|
|
887
|
+
);
|
|
888
|
+
assert.ok(
|
|
889
|
+
paneRegistrySource.includes('if (record.settled) return'),
|
|
890
|
+
'pane second settle is a no-op'
|
|
891
|
+
);
|
|
892
|
+
console.log('PASS timeout-vs-done keeps the deadline winner with a readable transcript');
|
|
893
|
+
|
|
894
|
+
// Close-cancels-watch: cancelled settles resolve blocked watchers but never
|
|
895
|
+
// enter the ledger; close drops pending entries and reports their ids.
|
|
896
|
+
const closeLedger = new UnseenCompletionLedger();
|
|
897
|
+
const closeRegistry = new LifecycleRegistry();
|
|
898
|
+
const closeOff = closeRegistry.onTaskSettled((result, context) => {
|
|
899
|
+
closeLedger.record(result, context);
|
|
900
|
+
});
|
|
901
|
+
const closingAgent = closeRegistry.registerAgent({ agent: 'worker', label: 'closing' });
|
|
902
|
+
const closingTask = closeRegistry.createTask(closingAgent, PROMPT);
|
|
903
|
+
const cancelledDeliveries = [];
|
|
904
|
+
closeRegistry.watchTasks(closingTask.id, completion => cancelledDeliveries.push(completion));
|
|
905
|
+
closeRegistry.settleTask(closingTask.id, { status: 'cancelled', error: 'Agent was closed.' });
|
|
906
|
+
assert.equal(cancelledDeliveries.length, 1, 'a blocked watch resolves with the cancellation');
|
|
907
|
+
assert.equal(cancelledDeliveries[0].status, 'cancelled');
|
|
908
|
+
assert.equal(closeLedger.pending().length, 0, 'the cancellation never enters the ledger');
|
|
909
|
+
closeOff();
|
|
910
|
+
const hcCloseLedger = new UnseenCompletionLedger();
|
|
911
|
+
const hcCloseOff = onHcTaskSettled((result, context) => {
|
|
912
|
+
hcCloseLedger.record(result, context);
|
|
913
|
+
});
|
|
914
|
+
notifyHcTaskSettledObservers(
|
|
915
|
+
{
|
|
916
|
+
taskId: 'shepherd-task-hc-matrix-cancelled',
|
|
917
|
+
agentId: hcAgentId,
|
|
918
|
+
status: 'cancelled',
|
|
919
|
+
ok: false,
|
|
920
|
+
returnCode: 130,
|
|
921
|
+
error: 'Agent was closed.',
|
|
922
|
+
completedAt: Date.now(),
|
|
923
|
+
},
|
|
924
|
+
{ hadWatchers: true, agent: 'worker', label: 'closing' }
|
|
925
|
+
);
|
|
926
|
+
assert.equal(
|
|
927
|
+
hcCloseLedger.pending().length,
|
|
928
|
+
0,
|
|
929
|
+
'hc cancellation records nothing even when watched'
|
|
930
|
+
);
|
|
931
|
+
hcCloseLedger.record(
|
|
932
|
+
{
|
|
933
|
+
taskId: 'shepherd-task-hc-matrix-drop',
|
|
934
|
+
agentId: hcAgentId,
|
|
935
|
+
status: 'completed',
|
|
936
|
+
ok: true,
|
|
937
|
+
returnCode: 0,
|
|
938
|
+
text: SUMMARY,
|
|
939
|
+
},
|
|
940
|
+
{ hadWatchers: false, agent: 'worker', label: 'closing' }
|
|
941
|
+
);
|
|
942
|
+
assert.deepEqual(hcCloseLedger.clearForAgent(hcAgentId), ['shepherd-task-hc-matrix-drop']);
|
|
943
|
+
assert.equal(hcCloseLedger.pending().length, 0, 'close drops the agent ledger clean');
|
|
944
|
+
hcCloseOff();
|
|
945
|
+
const shepherdSource = readFileSync(
|
|
946
|
+
new URL('../src/extension/shepherd.ts', import.meta.url),
|
|
947
|
+
'utf8'
|
|
948
|
+
);
|
|
949
|
+
assert.ok(shepherdSource.includes('clearForAgent'), 'close clears pending entries per agent');
|
|
950
|
+
assert.ok(shepherdSource.includes('clearedUnseenCompletions'), 'close reports the dropped ids');
|
|
951
|
+
assert.ok(hcRuntimeSource.includes("status: 'cancelled'"), 'hc close settles cancelled');
|
|
952
|
+
console.log('PASS close cancels the watch, keeps the ledger clean, and reports dropped ids');
|
|
953
|
+
}
|
|
954
|
+
|
|
955
|
+
// ── hc bridge seam (010 Phase 2): the production bridge delivers hc ─────
|
|
956
|
+
// settles exactly like Herdr settles — one boundary continuation while
|
|
957
|
+
// busy, one coalesced idle wake per burst, retrieval clear instead of a
|
|
958
|
+
// duplicate notice. Runs through `subscribeToTaskSettlements` (both
|
|
959
|
+
// registries) with an isolated ledger and a small injected coalesce window.
|
|
960
|
+
{
|
|
961
|
+
const sent = [];
|
|
962
|
+
const handlers = new Map();
|
|
963
|
+
const fakePi = {
|
|
964
|
+
registerMessageRenderer() {},
|
|
965
|
+
on(event, handler) {
|
|
966
|
+
const list = handlers.get(event) ?? [];
|
|
967
|
+
list.push(handler);
|
|
968
|
+
handlers.set(event, list);
|
|
969
|
+
},
|
|
970
|
+
sendMessage(message, options) {
|
|
971
|
+
sent.push({ message, options });
|
|
972
|
+
},
|
|
973
|
+
};
|
|
974
|
+
const fire = async (event, payload, ctx) => {
|
|
975
|
+
const results = [];
|
|
976
|
+
for (const handler of handlers.get(event) ?? []) results.push(await handler(payload, ctx));
|
|
977
|
+
return results;
|
|
978
|
+
};
|
|
979
|
+
const bridgeLedger = new UnseenCompletionLedger();
|
|
980
|
+
configureUnseenCompletionBridge(fakePi, { coalesceMs: 15, ledger: bridgeLedger });
|
|
981
|
+
await fire('session_start', { type: 'session_start' }, { isIdle: () => true });
|
|
982
|
+
|
|
983
|
+
// Idle burst on the hc path: one coalesced triggerTurn wake, then drained.
|
|
984
|
+
const hcIdleTask = 'shepherd-task-hc-matrix-idle';
|
|
985
|
+
const hcIdleAgent = 'shepherd-agent-hc-matrix-idle';
|
|
986
|
+
notifyHcTaskSettledObservers(
|
|
987
|
+
{
|
|
988
|
+
taskId: hcIdleTask,
|
|
989
|
+
agentId: hcIdleAgent,
|
|
990
|
+
status: 'completed',
|
|
991
|
+
ok: true,
|
|
992
|
+
returnCode: 0,
|
|
993
|
+
text: 'idle hc done',
|
|
994
|
+
completedAt: Date.now(),
|
|
995
|
+
},
|
|
996
|
+
{ hadWatchers: false, agent: 'worker', label: 'bridge-idle' }
|
|
997
|
+
);
|
|
998
|
+
await delay(60);
|
|
999
|
+
assert.equal(sent.length, 1, 'an idle hc burst wakes exactly once');
|
|
1000
|
+
assert.deepEqual(sent[0].options, { triggerTurn: true });
|
|
1001
|
+
assert.match(sent[0].message.content, /no watcher attached/);
|
|
1002
|
+
assert.ok(sent[0].message.content.includes(hcIdleTask));
|
|
1003
|
+
assert.deepEqual(sent[0].message.details.taskIds, [hcIdleTask]);
|
|
1004
|
+
assert.match(sent[0].message.content, /Full results: shepherd_watch/);
|
|
1005
|
+
assert.equal(bridgeLedger.pending().length, 0, 'the idle wake drains the ledger');
|
|
1006
|
+
console.log('PASS an idle hc settle fires one coalesced wake and drains');
|
|
1007
|
+
|
|
1008
|
+
// Retrieval clear (the ledger call shepherd_watch makes): no duplicate.
|
|
1009
|
+
const hcRetrievedTask = 'shepherd-task-hc-matrix-retrieved';
|
|
1010
|
+
notifyHcTaskSettledObservers(
|
|
1011
|
+
{
|
|
1012
|
+
taskId: hcRetrievedTask,
|
|
1013
|
+
agentId: hcIdleAgent,
|
|
1014
|
+
status: 'completed',
|
|
1015
|
+
ok: true,
|
|
1016
|
+
returnCode: 0,
|
|
1017
|
+
text: 'retrieved hc done',
|
|
1018
|
+
completedAt: Date.now(),
|
|
1019
|
+
},
|
|
1020
|
+
{ hadWatchers: false, agent: 'worker', label: 'bridge-idle' }
|
|
1021
|
+
);
|
|
1022
|
+
assert.deepEqual(bridgeLedger.clear([hcRetrievedTask]), [hcRetrievedTask]);
|
|
1023
|
+
await delay(50);
|
|
1024
|
+
assert.equal(sent.length, 1, 'no notice follows a retrieval clear');
|
|
1025
|
+
console.log('PASS shepherd_watch retrieval clears the hc entry with no duplicate notice');
|
|
1026
|
+
|
|
1027
|
+
// Busy hc settle: no mid-turn wake; one continuation at the completed boundary.
|
|
1028
|
+
await fire('agent_start', { type: 'agent_start' }, { isIdle: () => false });
|
|
1029
|
+
const hcBusyTask = 'shepherd-task-hc-matrix-busy';
|
|
1030
|
+
notifyHcTaskSettledObservers(
|
|
1031
|
+
{
|
|
1032
|
+
taskId: hcBusyTask,
|
|
1033
|
+
agentId: hcIdleAgent,
|
|
1034
|
+
status: 'completed',
|
|
1035
|
+
ok: true,
|
|
1036
|
+
returnCode: 0,
|
|
1037
|
+
text: 'busy hc done',
|
|
1038
|
+
completedAt: Date.now(),
|
|
1039
|
+
},
|
|
1040
|
+
{ hadWatchers: false, agent: 'worker', label: 'bridge-busy' }
|
|
1041
|
+
);
|
|
1042
|
+
await delay(50);
|
|
1043
|
+
assert.equal(sent.length, 1, 'no idle wake fires while the Shepherd is busy');
|
|
1044
|
+
const boundary = (
|
|
1045
|
+
await fire(
|
|
1046
|
+
'agent_before_settle',
|
|
1047
|
+
{ type: 'agent_before_settle', outcome: 'completed', context: { canContinue: false } },
|
|
1048
|
+
{ isIdle: () => false }
|
|
1049
|
+
)
|
|
1050
|
+
)[0];
|
|
1051
|
+
assert.ok(boundary, 'a completed boundary offers a continuation for the hc settle');
|
|
1052
|
+
assert.equal(boundary.continue, true);
|
|
1053
|
+
assert.deepEqual(boundary.entries[0].details.taskIds, [hcBusyTask]);
|
|
1054
|
+
assert.equal(bridgeLedger.pending().length, 0, 'the boundary drains the hc entry');
|
|
1055
|
+
assert.equal(sent.length, 1, 'the boundary delivers in-turn instead of via sendMessage');
|
|
1056
|
+
console.log('PASS a busy hc settle is delivered once at the completed settle boundary');
|
|
1057
|
+
|
|
1058
|
+
await fire('session_shutdown', { type: 'session_shutdown' }, { isIdle: () => true });
|
|
1059
|
+
}
|
|
1060
|
+
|
|
1061
|
+
// ── Phase 3: deadline drains inbox before settling timeout (010 §3) ───────
|
|
1062
|
+
// Live bug: the bare hc delegate `setTimeout(deadline)` settled `timed_out`
|
|
1063
|
+
// without draining, so a `task_done` already queued in the parent inbox lost
|
|
1064
|
+
// the race. The `watch` loop already drain-then-checks; the timer now does
|
|
1065
|
+
// the same. Deterministic, no live spawn: source-order assertion plus
|
|
1066
|
+
// first-wins semantics on both settlement paths, with transcript
|
|
1067
|
+
// readability and single-winner unseen entries.
|
|
1068
|
+
{
|
|
1069
|
+
const hcRuntimeSource = readFileSync(
|
|
1070
|
+
new URL('../src/runtimes/hc/runtime.ts', import.meta.url),
|
|
1071
|
+
'utf8'
|
|
1072
|
+
);
|
|
1073
|
+
assert.ok(
|
|
1074
|
+
/record\.timeoutId = setTimeout\(\(\) => \{[\s\S]*?drainBrokerInbox\(\)[\s\S]*?status: 'timed_out'/.test(
|
|
1075
|
+
hcRuntimeSource
|
|
1076
|
+
),
|
|
1077
|
+
'hc deadline timer drains the parent inbox before it may settle timed_out'
|
|
1078
|
+
);
|
|
1079
|
+
assert.ok(
|
|
1080
|
+
hcRuntimeSource.includes('drainBrokerInbox();') &&
|
|
1081
|
+
hcRuntimeSource.includes("source: 'delegate-submission-failure'"),
|
|
1082
|
+
'hc drain-first timer leaves the delegate-submission-failure path unchanged'
|
|
1083
|
+
);
|
|
1084
|
+
console.log('PASS hc deadline timer drains the inbox before settling timeout');
|
|
1085
|
+
|
|
1086
|
+
// Done-in-inbox-before-deadline wins: completed settles first, the expired
|
|
1087
|
+
// deadline attempt is a no-op, no timeout entry arises.
|
|
1088
|
+
const doneFirstRegistry = new LifecycleRegistry();
|
|
1089
|
+
const doneFirstEvents = [];
|
|
1090
|
+
const doneFirstOff = doneFirstRegistry.onTaskSettled((result, context) => {
|
|
1091
|
+
doneFirstEvents.push({ result, context });
|
|
1092
|
+
});
|
|
1093
|
+
const doneFirstAgent = doneFirstRegistry.registerAgent({ agent: 'worker', label: 'deadline-drain' });
|
|
1094
|
+
const doneFirstTask = doneFirstRegistry.createTask(doneFirstAgent, 'drain-first probe');
|
|
1095
|
+
doneFirstRegistry.setTaskRunning(doneFirstTask.id);
|
|
1096
|
+
doneFirstRegistry.settleTask(doneFirstTask.id, { status: 'completed', text: 'done was already queued' });
|
|
1097
|
+
const deadlineLoser = doneFirstRegistry.settleTask(doneFirstTask.id, {
|
|
1098
|
+
status: 'timed_out',
|
|
1099
|
+
error: 'Tracked task deadline reached.',
|
|
1100
|
+
});
|
|
1101
|
+
assert.equal(deadlineLoser.status, 'completed', 'an expired deadline cannot overwrite a queued done');
|
|
1102
|
+
assert.equal(doneFirstEvents.length, 1, 'the deadline loser is never observed');
|
|
1103
|
+
assert.equal(doneFirstRegistry.taskResult(doneFirstTask.id).status, 'completed');
|
|
1104
|
+
assert.equal(doneFirstRegistry.taskResult(doneFirstTask.id).text, 'done was already queued');
|
|
1105
|
+
doneFirstOff();
|
|
1106
|
+
const doneFirstLedger = new UnseenCompletionLedger();
|
|
1107
|
+
const doneFirstHcOff = onHcTaskSettled((result, context) => {
|
|
1108
|
+
doneFirstLedger.record(result, context);
|
|
1109
|
+
});
|
|
1110
|
+
const doneFirstHcTask = 'shepherd-task-hc-deadline-drain-done';
|
|
1111
|
+
const doneFirstHcAgent = 'shepherd-agent-hc-deadline-drain';
|
|
1112
|
+
notifyHcTaskSettledObservers(
|
|
1113
|
+
{
|
|
1114
|
+
taskId: doneFirstHcTask,
|
|
1115
|
+
agentId: doneFirstHcAgent,
|
|
1116
|
+
status: 'completed',
|
|
1117
|
+
ok: true,
|
|
1118
|
+
returnCode: 0,
|
|
1119
|
+
text: 'done was already queued',
|
|
1120
|
+
completedAt: Date.now(),
|
|
1121
|
+
},
|
|
1122
|
+
{ hadWatchers: false, agent: 'worker', label: 'deadline-drain' }
|
|
1123
|
+
);
|
|
1124
|
+
notifyHcTaskSettledObservers(
|
|
1125
|
+
{
|
|
1126
|
+
taskId: doneFirstHcTask,
|
|
1127
|
+
agentId: doneFirstHcAgent,
|
|
1128
|
+
status: 'timed_out',
|
|
1129
|
+
ok: false,
|
|
1130
|
+
returnCode: 124,
|
|
1131
|
+
error: 'Tracked task deadline reached.',
|
|
1132
|
+
completedAt: Date.now(),
|
|
1133
|
+
},
|
|
1134
|
+
{ hadWatchers: false, agent: 'worker', label: 'deadline-drain' }
|
|
1135
|
+
);
|
|
1136
|
+
doneFirstHcOff();
|
|
1137
|
+
assert.equal(doneFirstLedger.pending().length, 1, 'single winner-only entry when done was queued');
|
|
1138
|
+
assert.equal(doneFirstLedger.pending()[0].status, 'completed');
|
|
1139
|
+
assert.equal(doneFirstLedger.pending()[0].text, 'done was already queued');
|
|
1140
|
+
console.log('PASS done-in-inbox-before-deadline wins with no timeout entry');
|
|
1141
|
+
|
|
1142
|
+
// Empty inbox + expired deadline: timed_out settles and is itself an unseen
|
|
1143
|
+
// entry when unwatched; a late done afterwards is ignored with a readable
|
|
1144
|
+
// winning transcript and still a single entry.
|
|
1145
|
+
const timeoutRegistry = new LifecycleRegistry();
|
|
1146
|
+
const timeoutEvents = [];
|
|
1147
|
+
const timeoutOff = timeoutRegistry.onTaskSettled((result, context) => {
|
|
1148
|
+
timeoutEvents.push({ result, context });
|
|
1149
|
+
});
|
|
1150
|
+
const timeoutAgent = timeoutRegistry.registerAgent({ agent: 'worker', label: 'deadline-empty' });
|
|
1151
|
+
const timeoutTask = timeoutRegistry.createTask(timeoutAgent, 'empty inbox probe');
|
|
1152
|
+
timeoutRegistry.setTaskRunning(timeoutTask.id);
|
|
1153
|
+
timeoutRegistry.settleTask(timeoutTask.id, {
|
|
1154
|
+
status: 'timed_out',
|
|
1155
|
+
error: 'Tracked task deadline reached.',
|
|
1156
|
+
});
|
|
1157
|
+
const lateDone = timeoutRegistry.settleTask(timeoutTask.id, {
|
|
1158
|
+
status: 'completed',
|
|
1159
|
+
text: 'late done',
|
|
1160
|
+
});
|
|
1161
|
+
assert.equal(lateDone.status, 'timed_out', 'a late done cannot overwrite the deadline');
|
|
1162
|
+
assert.equal(timeoutEvents.length, 1, 'the late done is never observed');
|
|
1163
|
+
assert.equal(timeoutRegistry.taskResult(timeoutTask.id).status, 'timed_out');
|
|
1164
|
+
assert.equal(timeoutRegistry.taskResult(timeoutTask.id).error, 'Tracked task deadline reached.');
|
|
1165
|
+
timeoutOff();
|
|
1166
|
+
const timeoutLedger = new UnseenCompletionLedger();
|
|
1167
|
+
const timeoutHcOff = onHcTaskSettled((result, context) => {
|
|
1168
|
+
timeoutLedger.record(result, context);
|
|
1169
|
+
});
|
|
1170
|
+
const timeoutHcTask = 'shepherd-task-hc-deadline-timeout';
|
|
1171
|
+
notifyHcTaskSettledObservers(
|
|
1172
|
+
{
|
|
1173
|
+
taskId: timeoutHcTask,
|
|
1174
|
+
agentId: doneFirstHcAgent,
|
|
1175
|
+
status: 'timed_out',
|
|
1176
|
+
ok: false,
|
|
1177
|
+
returnCode: 124,
|
|
1178
|
+
error: 'Tracked task deadline reached.',
|
|
1179
|
+
completedAt: Date.now(),
|
|
1180
|
+
},
|
|
1181
|
+
{ hadWatchers: false, agent: 'worker', label: 'deadline-empty' }
|
|
1182
|
+
);
|
|
1183
|
+
assert.equal(timeoutLedger.pending().length, 1, 'an unwatched timeout is itself an unseen entry');
|
|
1184
|
+
assert.equal(timeoutLedger.pending()[0].status, 'timed_out');
|
|
1185
|
+
assert.match(
|
|
1186
|
+
formatUnseenCompletionNotice(timeoutLedger.pending()),
|
|
1187
|
+
/timed_out/
|
|
1188
|
+
);
|
|
1189
|
+
notifyHcTaskSettledObservers(
|
|
1190
|
+
{
|
|
1191
|
+
taskId: timeoutHcTask,
|
|
1192
|
+
agentId: doneFirstHcAgent,
|
|
1193
|
+
status: 'completed',
|
|
1194
|
+
ok: true,
|
|
1195
|
+
returnCode: 0,
|
|
1196
|
+
text: 'late done',
|
|
1197
|
+
completedAt: Date.now(),
|
|
1198
|
+
},
|
|
1199
|
+
{ hadWatchers: false, agent: 'worker', label: 'deadline-empty' }
|
|
1200
|
+
);
|
|
1201
|
+
timeoutHcOff();
|
|
1202
|
+
assert.equal(timeoutLedger.pending().length, 1, 'late done keeps a single winner-only entry');
|
|
1203
|
+
assert.equal(timeoutLedger.pending()[0].status, 'timed_out');
|
|
1204
|
+
console.log('PASS empty inbox times out as unseen; late done is ignored with a readable winner');
|
|
1205
|
+
}
|
|
1206
|
+
|
|
1207
|
+
function ledgerCount(ledger) {
|
|
1208
|
+
return ledger.pending().length;
|
|
1209
|
+
}
|
|
1210
|
+
|
|
1211
|
+
console.log('All unseen-completion assertions passed.');
|