@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.
Files changed (204) hide show
  1. package/.agents/agents/README.md +12 -0
  2. package/.agents/agents/planner.md +38 -0
  3. package/.agents/agents/reviewer.md +38 -0
  4. package/.agents/agents/scout.md +43 -0
  5. package/.agents/agents/worker.md +33 -0
  6. package/.agents/skills/smoke-test/SKILL.md +155 -0
  7. package/.agents/skills/smoke-test/references/forensics.md +46 -0
  8. package/.agents/skills/smoke-test/scripts/live-smoke-poll.mjs +130 -0
  9. package/.github/workflows/publish.yml +77 -0
  10. package/.pi/prompts/release.md +21 -0
  11. package/.prettierrc +10 -0
  12. package/AGENTS.md +88 -0
  13. package/CONTRIBUTING.md +177 -0
  14. package/LICENSE +201 -0
  15. package/README.md +397 -2
  16. package/docs/README.md +26 -0
  17. package/docs/guides/agent-definitions.md +42 -0
  18. package/docs/guides/diagnostics.md +199 -0
  19. package/docs/guides/installation.md +61 -0
  20. package/docs/guides/tool-reference.md +55 -0
  21. package/docs/manual-tests/ping-pong-peer-messaging.md +147 -0
  22. package/docs/plans/agent-labels.md +257 -0
  23. package/docs/plans/architecture.md +110 -0
  24. package/docs/plans/settings-scope.md +163 -0
  25. package/docs/plans/tool-surface-split.md +278 -0
  26. package/docs/reference/dictionary +26 -0
  27. package/docs/releasing.md +47 -0
  28. package/docs/specs/005-agent-messaging-and-task-lifecycle/baseline.md +115 -0
  29. package/docs/specs/005-agent-messaging-and-task-lifecycle/handoff.md +564 -0
  30. package/docs/specs/005-agent-messaging-and-task-lifecycle/phase10-notes.md +109 -0
  31. package/docs/specs/005-agent-messaging-and-task-lifecycle/phase6-notes.md +69 -0
  32. package/docs/specs/005-agent-messaging-and-task-lifecycle/phase7-notes.md +100 -0
  33. package/docs/specs/005-agent-messaging-and-task-lifecycle/phase8-notes.md +127 -0
  34. package/docs/specs/005-agent-messaging-and-task-lifecycle/phase9-notes.md +104 -0
  35. package/docs/specs/005-agent-messaging-and-task-lifecycle/plan.md +1093 -0
  36. package/docs/specs/005-agent-messaging-and-task-lifecycle/spec.md +583 -0
  37. package/docs/specs/005-agent-messaging-and-task-lifecycle/tasks.md +838 -0
  38. package/docs/specs/006-shepherd-tool-rendering/plan.md +175 -0
  39. package/docs/specs/006-shepherd-tool-rendering/spec.md +469 -0
  40. package/index.ts +602 -0
  41. package/package.json +112 -4
  42. package/scripts/capture-system-prompt.mjs +45 -0
  43. package/scripts/extract-pi-system-prompt.mjs +277 -0
  44. package/scripts/host-impact.mjs +74 -0
  45. package/scripts/resolve-agent.mjs +43 -0
  46. package/scripts/show-shepherd-orchestrator.mjs +58 -0
  47. package/scripts/show-shepherd-prompt.mjs +96 -0
  48. package/scripts/verify-suites.mjs +67 -0
  49. package/specs/001-artifacts/spec.md +436 -0
  50. package/specs/002-simplify-agent-orchestration/plan.md +287 -0
  51. package/specs/002-simplify-agent-orchestration/spec.md +323 -0
  52. package/specs/002-simplify-agent-orchestration/tasks.md +212 -0
  53. package/specs/003-orchestrator-session-artifacts/plan.md +396 -0
  54. package/specs/003-orchestrator-session-artifacts/spec.md +453 -0
  55. package/specs/003-orchestrator-session-artifacts/tasks.md +141 -0
  56. package/specs/004-asynchronous-prompt-watchers/plan.md +139 -0
  57. package/specs/004-asynchronous-prompt-watchers/spec.md +202 -0
  58. package/specs/004-asynchronous-prompt-watchers/tasks.md +126 -0
  59. package/specs/005-per-workspace-settings/plan.md +230 -0
  60. package/specs/005-per-workspace-settings/spec.md +368 -0
  61. package/specs/005-per-workspace-settings/tasks.md +178 -0
  62. package/specs/006-dual-runtime-herdr-durable/intent.md +86 -0
  63. package/specs/006-dual-runtime-herdr-durable/journal.md +80 -0
  64. package/specs/006-dual-runtime-herdr-durable/plan.md +242 -0
  65. package/specs/006-dual-runtime-herdr-durable/spec.md +389 -0
  66. package/specs/006-dual-runtime-herdr-durable/tasks.md +199 -0
  67. package/specs/007-unwatched-completion-notice/journal.md +145 -0
  68. package/specs/007-unwatched-completion-notice/plan.md +186 -0
  69. package/specs/007-unwatched-completion-notice/spec.md +284 -0
  70. package/specs/007-unwatched-completion-notice/tasks.md +147 -0
  71. package/specs/008-remote-machine-sheep/intent.md +174 -0
  72. package/specs/008-remote-machine-sheep/journal.md +57 -0
  73. package/specs/008-remote-machine-sheep/prerequisites.md +219 -0
  74. package/specs/009-hc-runtime/intent.md +44 -0
  75. package/specs/009-hc-runtime/plan.md +49 -0
  76. package/specs/009-hc-runtime/spec.md +118 -0
  77. package/specs/009-hc-runtime/tasks.md +62 -0
  78. package/specs/010-unseen-watch-parity/intent.md +57 -0
  79. package/specs/010-unseen-watch-parity/journal.md +172 -0
  80. package/specs/010-unseen-watch-parity/plan.md +74 -0
  81. package/specs/010-unseen-watch-parity/spec.md +191 -0
  82. package/specs/010-unseen-watch-parity/tasks.md +119 -0
  83. package/specs/011-hc-background-poll/intent.md +57 -0
  84. package/specs/011-hc-background-poll/journal.md +95 -0
  85. package/specs/011-hc-background-poll/plan.md +87 -0
  86. package/specs/011-hc-background-poll/spec.md +141 -0
  87. package/specs/011-hc-background-poll/tasks.md +83 -0
  88. package/specs/012-steer-default/intent.md +12 -0
  89. package/specs/012-steer-default/journal.md +40 -0
  90. package/specs/012-steer-default/plan.md +7 -0
  91. package/specs/012-steer-default/spec.md +42 -0
  92. package/specs/012-steer-default/tasks.md +6 -0
  93. package/specs/013-opencode-shepherd/handoff-t011.md +94 -0
  94. package/specs/013-opencode-shepherd/intent.md +59 -0
  95. package/specs/013-opencode-shepherd/plan.md +204 -0
  96. package/specs/013-opencode-shepherd/spec.md +258 -0
  97. package/specs/013-opencode-shepherd/tasks.md +263 -0
  98. package/src/core/artifact-sessions.ts +835 -0
  99. package/src/core/config.ts +329 -0
  100. package/src/core/discovery.ts +342 -0
  101. package/src/core/herdr.ts +1 -0
  102. package/src/core/host.ts +77 -0
  103. package/src/core/ids.ts +78 -0
  104. package/src/core/lifecycle.ts +1 -0
  105. package/src/core/messaging.ts +1 -0
  106. package/src/core/migration.ts +55 -0
  107. package/src/core/orchestration.ts +1 -0
  108. package/src/core/types.ts +143 -0
  109. package/src/core/unseen-completions.ts +114 -0
  110. package/src/extension/cli.ts +417 -0
  111. package/src/extension/config.ts +1 -0
  112. package/src/extension/settings-ui.ts +296 -0
  113. package/src/extension/shepherd-done.ts +768 -0
  114. package/src/extension/shepherd.ts +2548 -0
  115. package/src/extension/system-prompt.ts +38 -0
  116. package/src/extension/unseen-completions.ts +237 -0
  117. package/src/opencode/actions.ts +794 -0
  118. package/src/opencode/bridge.ts +777 -0
  119. package/src/opencode/display.ts +36 -0
  120. package/src/opencode/fieldnotes.ts +60 -0
  121. package/src/opencode/host.ts +62 -0
  122. package/src/opencode/orphans.ts +162 -0
  123. package/src/opencode/server.ts +458 -0
  124. package/src/runtimes/backend.ts +119 -0
  125. package/src/runtimes/detect.ts +102 -0
  126. package/src/runtimes/hc/hc.ts +527 -0
  127. package/src/runtimes/hc/runtime.ts +1898 -0
  128. package/src/runtimes/herdr/herdr.ts +912 -0
  129. package/src/runtimes/herdr/lifecycle.ts +1712 -0
  130. package/src/runtimes/herdr/messaging.ts +703 -0
  131. package/src/runtimes/herdr/orchestration.ts +1583 -0
  132. package/src/runtimes/herdr/runtime.ts +224 -0
  133. package/src/runtimes/runtime.ts +133 -0
  134. package/src/runtimes/settle-observations.ts +114 -0
  135. package/test/fixtures/context-project/AGENTS.md +2 -0
  136. package/test/fixtures/home/.agents/agents/same.md +6 -0
  137. package/test/fixtures/home/.agents/agents/shared-only.md +6 -0
  138. package/test/fixtures/home/.pi/agent/agents/invalid-thinking.md +6 -0
  139. package/test/fixtures/home/.pi/agent/agents/model-empty.md +7 -0
  140. package/test/fixtures/home/.pi/agent/agents/model-explicit.md +7 -0
  141. package/test/fixtures/home/.pi/agent/agents/omit-context-absent.md +5 -0
  142. package/test/fixtures/home/.pi/agent/agents/omit-context-false.md +6 -0
  143. package/test/fixtures/home/.pi/agent/agents/omit-context-invalid.md +6 -0
  144. package/test/fixtures/home/.pi/agent/agents/omit-context-true.md +6 -0
  145. package/test/fixtures/home/.pi/agent/agents/omit-false.md +6 -0
  146. package/test/fixtures/home/.pi/agent/agents/omit-invalid.md +6 -0
  147. package/test/fixtures/home/.pi/agent/agents/omit-pi-docs.md +7 -0
  148. package/test/fixtures/home/.pi/agent/agents/omit-true.md +6 -0
  149. package/test/fixtures/home/.pi/agent/agents/only-user.md +9 -0
  150. package/test/fixtures/home/.pi/agent/agents/same.md +6 -0
  151. package/test/fixtures/proj/.agents/agents/proj-shared.md +6 -0
  152. package/test/fixtures/proj/.pi/agents/project-pi.md +6 -0
  153. package/test/fixtures/proj/.pi/agents/same.md +6 -0
  154. package/test/helpers/fake-clock.mjs +39 -0
  155. package/test/helpers/feature-contracts.mjs +44 -0
  156. package/test/helpers/test-utils.mjs +44 -0
  157. package/test/verify-artifact-sessions.mjs +258 -0
  158. package/test/verify-backend.mjs +297 -0
  159. package/test/verify-child-mislabel.mjs +135 -0
  160. package/test/verify-child-surface.mjs +321 -0
  161. package/test/verify-cli.mjs +197 -0
  162. package/test/verify-command-ux.mjs +100 -0
  163. package/test/verify-compat.mjs +32 -0
  164. package/test/verify-cross-host-notes.mjs +128 -0
  165. package/test/verify-delegate.mjs +161 -0
  166. package/test/verify-detect.mjs +151 -0
  167. package/test/verify-discovery.mjs +239 -0
  168. package/test/verify-done-nudge.mjs +238 -0
  169. package/test/verify-effective-prompt.mjs +98 -0
  170. package/test/verify-hc-matrix.mjs +246 -0
  171. package/test/verify-hc-poll.mjs +260 -0
  172. package/test/verify-host-docs.mjs +66 -0
  173. package/test/verify-host-impact.mjs +49 -0
  174. package/test/verify-ids.mjs +141 -0
  175. package/test/verify-launch.mjs +183 -0
  176. package/test/verify-message-routing.mjs +560 -0
  177. package/test/verify-messaging.mjs +303 -0
  178. package/test/verify-migration-notice.mjs +74 -0
  179. package/test/verify-multi-wait.mjs +42 -0
  180. package/test/verify-opencode-display.mjs +47 -0
  181. package/test/verify-opencode-fieldnotes.mjs +121 -0
  182. package/test/verify-opencode-notice.mjs +77 -0
  183. package/test/verify-opencode-nudge.mjs +116 -0
  184. package/test/verify-opencode-orphans.mjs +160 -0
  185. package/test/verify-opencode-surface.mjs +107 -0
  186. package/test/verify-packaging.mjs +82 -0
  187. package/test/verify-parent-surface.mjs +118 -0
  188. package/test/verify-phase0.mjs +95 -0
  189. package/test/verify-registry.mjs +124 -0
  190. package/test/verify-rename-migration.mjs +111 -0
  191. package/test/verify-rendering.mjs +379 -0
  192. package/test/verify-session-boundary.mjs +146 -0
  193. package/test/verify-settings.mjs +260 -0
  194. package/test/verify-stale-wait.mjs +339 -0
  195. package/test/verify-status-widget.mjs +377 -0
  196. package/test/verify-status.mjs +172 -0
  197. package/test/verify-task-completion.mjs +156 -0
  198. package/test/verify-task-failures.mjs +201 -0
  199. package/test/verify-task-mislabel.mjs +143 -0
  200. package/test/verify-task-registry.mjs +194 -0
  201. package/test/verify-task-watchers.mjs +217 -0
  202. package/test/verify-tool-schemas.mjs +120 -0
  203. package/test/verify-unseen-completions.mjs +1211 -0
  204. package/test/verify-watchers.mjs +181 -0
@@ -0,0 +1,146 @@
1
+ #!/usr/bin/env node
2
+ /** Regression coverage for lifecycle state leaking across pi sessions. */
3
+ import assert from 'node:assert/strict';
4
+ import { mkdtempSync } from 'node:fs';
5
+ import { tmpdir } from 'node:os';
6
+ import * as path from 'node:path';
7
+ import { LifecycleError, LifecycleRegistry, lifecycleRegistry } from '../src/core/orchestration.ts';
8
+
9
+ function expectUnknown(fn, label, code = 'unknown_handle') {
10
+ assert.throws(fn, error => {
11
+ assert.ok(error instanceof LifecycleError, `${label}: expected LifecycleError`);
12
+ assert.equal(error.code, code, `${label}: expected ${code}`);
13
+ return true;
14
+ });
15
+ console.log(`PASS ${label}`);
16
+ }
17
+
18
+ // Core registry behavior: a repeated session_start for the same parent must be
19
+ // idempotent, while a different parent session gets a fresh lifecycle namespace.
20
+ const registry = new LifecycleRegistry();
21
+ registry.beginSession('parent-session-a');
22
+ const oldTester = registry.registerAgent({ agent: 'tester', label: 'task 1 color adjustment' });
23
+ const oldWorker = registry.registerAgent({ agent: 'worker', label: 'task 1 color adjustment' });
24
+ const oldTask = registry.createTask(oldTester, 'Old session task');
25
+ const oldPrompt = registry.createPrompt(oldTester);
26
+ // Settle before switching so this focused test does not leave the prompt's
27
+ // long safety timer alive; the handle should still be rejected after rollover.
28
+ registry.settlePrompt(oldPrompt, {
29
+ promptId: oldPrompt.id,
30
+ agentId: oldTester.id,
31
+ status: 'done',
32
+ ok: true,
33
+ });
34
+
35
+ assert.throws(
36
+ () => registry.registerAgent({ agent: 'tester', label: 'task 1 color adjustment' }),
37
+ /Duplicate agent label/,
38
+ 'same-session duplicate remains rejected'
39
+ );
40
+ console.log('PASS same-session duplicate remains rejected');
41
+
42
+ registry.beginSession('parent-session-a');
43
+ assert.throws(
44
+ () => registry.registerAgent({ agent: 'tester', label: 'task 1 color adjustment' }),
45
+ /Duplicate agent label/,
46
+ 'repeated session_start for the same session does not reset the registry'
47
+ );
48
+ console.log('PASS repeated session_start for the same session does not reset the registry');
49
+
50
+ registry.beginSession('parent-session-b');
51
+ const freshTester = registry.registerAgent({ agent: 'tester', label: 'task 1 color adjustment' });
52
+ assert.notEqual(freshTester.id, oldTester.id, 'new session receives a new opaque agent id');
53
+ assert.equal(registry.allAgents().length, 1, 'allAgents exposes only current-session agents');
54
+ assert.equal(registry.allAgents()[0].id, freshTester.id);
55
+ console.log('PASS identical label is reusable in a new session');
56
+ console.log('PASS old-session agents are excluded from current-session projections');
57
+
58
+ expectUnknown(
59
+ () => registry.getAgent(oldTester.id),
60
+ 'old agent id is rejected after a session switch'
61
+ );
62
+ expectUnknown(
63
+ () => registry.getAgent(oldWorker.id),
64
+ 'old peer agent id is rejected after a session switch'
65
+ );
66
+ expectUnknown(
67
+ () => registry.getTask(oldTask.id),
68
+ 'old task id is rejected after a session switch',
69
+ 'unknown_task'
70
+ );
71
+ expectUnknown(
72
+ () => registry.getPrompt(oldPrompt.id),
73
+ 'old prompt id is rejected after a session switch'
74
+ );
75
+ assert.deepEqual(
76
+ registry.allTasks(),
77
+ [],
78
+ 'old-session tasks are excluded from current-session projections'
79
+ );
80
+ console.log('PASS old-session tasks are excluded from current-session projections');
81
+
82
+ // A spawn can cross a session boundary while Herdr is starting the child. Its
83
+ // reserved id must not be registered into the new session accidentally.
84
+ const inFlightId = registry.allocateAgentId();
85
+ registry.beginSession('parent-session-c');
86
+ assert.throws(
87
+ () => registry.registerAgent({ id: inFlightId, agent: 'tester', label: 'in-flight spawn' }),
88
+ error => error instanceof LifecycleError && error.code === 'invalid_handle',
89
+ 'in-flight spawn ids cannot be registered after a session switch'
90
+ );
91
+ console.log('PASS in-flight spawn ids cannot be registered after a session switch');
92
+
93
+ // Integration boundary: exercise the actual index.ts session_start hook so the
94
+ // regression cannot be hidden by testing beginSession() without wiring it up.
95
+ const previousAgentDir = process.env.PI_CODING_AGENT_DIR;
96
+ process.env.PI_CODING_AGENT_DIR = mkdtempSync(path.join(tmpdir(), 'pi-shepherd-session-boundary-'));
97
+ try {
98
+ const calls = { events: [] };
99
+ const pi = {
100
+ registerTool() {},
101
+ registerCommand() {},
102
+ registerMessageRenderer() {},
103
+ on(event, handler) {
104
+ calls.events.push({ event, handler });
105
+ },
106
+ };
107
+ const { default: registerExtension } = await import('../index.ts');
108
+ registerExtension(pi);
109
+ const sessionStartHandlers = calls.events
110
+ .filter(entry => entry.event === 'session_start')
111
+ .map(entry => entry.handler);
112
+ assert.ok(sessionStartHandlers.length >= 2, 'parent extension registers session_start handlers');
113
+
114
+ const start = id => {
115
+ const context = {
116
+ hasUI: false,
117
+ cwd: process.cwd(),
118
+ sessionManager: { getSessionId: () => id },
119
+ };
120
+ for (const handler of sessionStartHandlers) handler({}, context);
121
+ };
122
+
123
+ start('hook-session-a');
124
+ const hookOld = lifecycleRegistry.registerAgent({ agent: 'tester', label: 'hook boundary' });
125
+ start('hook-session-a');
126
+ assert.throws(
127
+ () => lifecycleRegistry.registerAgent({ agent: 'tester', label: 'hook boundary' }),
128
+ /Duplicate agent label/,
129
+ 'the real hook keeps repeated starts in one session idempotent'
130
+ );
131
+ console.log('PASS the real hook keeps repeated starts in one session idempotent');
132
+
133
+ start('hook-session-b');
134
+ const hookFresh = lifecycleRegistry.registerAgent({ agent: 'tester', label: 'hook boundary' });
135
+ assert.notEqual(hookFresh.id, hookOld.id);
136
+ expectUnknown(
137
+ () => lifecycleRegistry.getAgent(hookOld.id),
138
+ 'the real hook retires old agent ids'
139
+ );
140
+ console.log('PASS the real hook allows a label to be reused by the new session');
141
+ } finally {
142
+ if (previousAgentDir === undefined) delete process.env.PI_CODING_AGENT_DIR;
143
+ else process.env.PI_CODING_AGENT_DIR = previousAgentDir;
144
+ }
145
+
146
+ console.log('All session-boundary assertions passed.');
@@ -0,0 +1,260 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * Filesystem-only verification for per-workspace Shepherd settings:
4
+ * user values in ~/.pi/agent/pi-shepherd/config.json and a self-contained
5
+ * .shepherd/config.json activated by projectScope: true.
6
+ */
7
+ import * as assert from 'node:assert/strict';
8
+ import * as fs from 'node:fs';
9
+ import * as os from 'node:os';
10
+ import * as path from 'node:path';
11
+
12
+ const home = fs.mkdtempSync(path.join(os.tmpdir(), 'pi-shepherd-settings-'));
13
+ const previousAgentDir = process.env.PI_CODING_AGENT_DIR;
14
+ process.env.PI_CODING_AGENT_DIR = path.join(home, '.pi', 'agent');
15
+
16
+ try {
17
+ const mod = await import(`../src/extension/config.ts?settings-test=${Date.now()}`);
18
+ const {
19
+ DEFAULT_SETTINGS,
20
+ deactivateProjectScope,
21
+ fieldnotesEnabled,
22
+ initializeSessionSettings,
23
+ loadProjectFileValues,
24
+ loadSettings,
25
+ projectConfigFile,
26
+ saveSettings,
27
+ userConfigFile,
28
+ } = mod;
29
+ const legacyFile = path.join(path.dirname(userConfigFile()), 'settings.json');
30
+
31
+ assert.equal(
32
+ userConfigFile(),
33
+ path.join(home, '.pi', 'agent', 'pi-shepherd', 'config.json'),
34
+ 'user config path honors PI_CODING_AGENT_DIR'
35
+ );
36
+ assert.equal(DEFAULT_SETTINGS.projectScope, false, 'default project scope is inactive');
37
+ assert.equal(
38
+ DEFAULT_SETTINGS.confirmProjectAgents,
39
+ false,
40
+ 'confirmation default is off'
41
+ );
42
+ assert.equal(DEFAULT_SETTINGS.stayOpen, true, 'keep-alive defaults on');
43
+ assert.equal(DEFAULT_SETTINGS.timeout, 60, 'default run timeout is 60 minutes');
44
+ assert.equal(
45
+ DEFAULT_SETTINGS.staleWaitThreshold,
46
+ 30,
47
+ 'default stale-wait threshold is 30 minutes'
48
+ );
49
+ assert.equal(loadSettings().fieldnotes, true, 'missing fieldnotes defaults on');
50
+ assert.equal(loadSettings().emojiSheep, true, 'missing sheep marker defaults on');
51
+
52
+ // --- user layer persistence: values only -------------------------------
53
+ const user = {
54
+ ...DEFAULT_SETTINGS,
55
+ fieldnotes: false,
56
+ emojiSheep: false,
57
+ confirmProjectAgents: false,
58
+ timeout: 25,
59
+ };
60
+ saveSettings(user, 'user');
61
+ const rawUser = JSON.parse(fs.readFileSync(userConfigFile(), 'utf8'));
62
+ assert.ok(!('projectScope' in rawUser), 'user file does not store projectScope');
63
+ assert.ok(!('settingsScope' in rawUser), 'user file does not store settingsScope');
64
+ assert.equal(rawUser.confirmProjectAgents, false, 'user file stores the security setting');
65
+ assert.equal(loadSettings().fieldnotes, false, 'user fieldnotes persists');
66
+ assert.equal(loadSettings().emojiSheep, false, 'user sheep marker persists');
67
+ assert.equal(loadSettings().timeout, 25, 'user timeout persists');
68
+ saveSettings({ ...user, timeout: 1_000 }, 'user');
69
+ assert.equal(loadSettings().timeout, 1, 'short legacy millisecond timeout clamps to one minute');
70
+ saveSettings(user, 'user');
71
+
72
+ // --- user scope keys are ignored and stripped on save ------------------
73
+ const noiseCwd = path.join(home, 'noise');
74
+ fs.mkdirSync(noiseCwd, { recursive: true });
75
+ fs.writeFileSync(
76
+ userConfigFile(),
77
+ JSON.stringify({ settingsScope: 'project', projectScope: true, timeout: 11 })
78
+ );
79
+ assert.equal(
80
+ loadSettings(noiseCwd).projectScope,
81
+ false,
82
+ 'user scope keys cannot activate a project'
83
+ );
84
+ assert.equal(loadSettings(noiseCwd).timeout, 11, 'user value still applies');
85
+ saveSettings({ ...DEFAULT_SETTINGS, timeout: 11 }, 'user');
86
+ const cleanedUser = JSON.parse(fs.readFileSync(userConfigFile(), 'utf8'));
87
+ assert.ok(!('settingsScope' in cleanedUser), 'user save strips legacy settingsScope');
88
+ assert.ok(!('projectScope' in cleanedUser), 'user save strips stray projectScope');
89
+
90
+ // Restore a deliberate user layer for project-resolution assertions.
91
+ saveSettings(user, 'user');
92
+ const cwd = path.join(home, 'project');
93
+ const otherCwd = path.join(home, 'other');
94
+ const freshCwd = path.join(home, 'fresh');
95
+ for (const dir of [cwd, otherCwd, freshCwd]) fs.mkdirSync(dir, { recursive: true });
96
+ const projectFile = projectConfigFile(cwd);
97
+
98
+ assert.equal(loadSettings(cwd).projectScope, false, 'no project file uses user scope');
99
+ assert.equal(loadSettings(cwd).timeout, 25, 'no project file uses user timeout');
100
+ assert.equal(
101
+ loadSettings(cwd).confirmProjectAgents,
102
+ false,
103
+ 'no project file uses user confirmation'
104
+ );
105
+
106
+ // --- dormant project files never override user values ------------------
107
+ fs.mkdirSync(path.dirname(projectFile), { recursive: true });
108
+ fs.writeFileSync(
109
+ projectFile,
110
+ JSON.stringify({
111
+ projectScope: false,
112
+ timeout: 30,
113
+ fieldnotes: true,
114
+ confirmProjectAgents: true,
115
+ })
116
+ );
117
+ assert.equal(loadSettings(cwd).projectScope, false, 'false flag leaves project dormant');
118
+ assert.equal(loadSettings(cwd).timeout, 25, 'dormant project timeout is ignored');
119
+ assert.equal(loadSettings(cwd).fieldnotes, false, 'dormant project fieldnotes are ignored');
120
+ assert.equal(loadSettings(cwd).confirmProjectAgents, false, 'project cannot own confirmation');
121
+
122
+ fs.writeFileSync(projectFile, JSON.stringify({ timeout: 30 }));
123
+ assert.equal(loadSettings(cwd).projectScope, false, 'keyless project file is dormant');
124
+ assert.equal(loadSettings(cwd).timeout, 25, 'keyless project values are dormant');
125
+
126
+ fs.writeFileSync(projectFile, JSON.stringify({ projectScope: 'yes', timeout: 30 }));
127
+ assert.equal(loadSettings(cwd).projectScope, false, 'invalid project flag is dormant');
128
+ assert.equal(loadSettings(cwd).timeout, 25, 'invalid project flag does not apply values');
129
+
130
+ // --- active project files are self-contained ---------------------------
131
+ fs.writeFileSync(
132
+ projectFile,
133
+ JSON.stringify({
134
+ projectScope: true,
135
+ timeout: 30,
136
+ fieldnotes: true,
137
+ confirmProjectAgents: true,
138
+ })
139
+ );
140
+ const active = loadSettings(cwd);
141
+ assert.equal(active.projectScope, true, 'true flag activates this workspace');
142
+ assert.equal(active.timeout, 30, 'active project timeout applies');
143
+ assert.equal(active.fieldnotes, true, 'active project fieldnotes apply');
144
+ assert.equal(active.emojiSheep, true, 'missing active field falls back to built-in default');
145
+ assert.equal(active.agentScope, 'both', 'missing active agent scope uses built-in default');
146
+ assert.equal(
147
+ active.confirmProjectAgents,
148
+ false,
149
+ 'active project cannot override user confirmation'
150
+ );
151
+ assert.equal(loadSettings().projectScope, false, 'no-cwd resolution remains user-scoped');
152
+ assert.equal(loadSettings(otherCwd).projectScope, false, 'another workspace is unaffected');
153
+ assert.equal(loadSettings(otherCwd).timeout, 25, 'another workspace retains user timeout');
154
+
155
+ // Legacy project scope is read-only compatible.
156
+ fs.writeFileSync(projectFile, JSON.stringify({ settingsScope: 'project', timeout: 31 }));
157
+ assert.equal(loadSettings(cwd).projectScope, true, 'legacy project settingsScope activates');
158
+ assert.equal(loadSettings(cwd).timeout, 31, 'legacy project values apply');
159
+ fs.writeFileSync(projectFile, JSON.stringify({ settingsScope: 'user', timeout: 31 }));
160
+ assert.equal(loadSettings(cwd).projectScope, false, 'legacy user scope does not activate');
161
+
162
+ // Malformed and non-object project files fall back to the user layer.
163
+ fs.writeFileSync(projectFile, 'not json');
164
+ assert.equal(loadSettings(cwd).projectScope, false, 'malformed project file is inactive');
165
+ assert.equal(loadSettings(cwd).timeout, 25, 'malformed project file uses user values');
166
+ fs.writeFileSync(projectFile, JSON.stringify([]));
167
+ assert.equal(loadSettings(cwd).projectScope, false, 'array project file is inactive');
168
+
169
+ // --- full project writes and fresh creation ----------------------------
170
+ let result = saveSettings(
171
+ { ...DEFAULT_SETTINGS, projectScope: true, timeout: 42, confirmProjectAgents: false },
172
+ 'project',
173
+ cwd
174
+ );
175
+ assert.equal(result.created, false, 'existing project file reports created=false');
176
+ const rawProject = JSON.parse(fs.readFileSync(projectFile, 'utf8'));
177
+ assert.equal(rawProject.projectScope, true, 'project save writes the activation flag');
178
+ assert.equal(rawProject.timeout, 42, 'project save writes project values');
179
+ assert.ok(!('confirmProjectAgents' in rawProject), 'project save omits user-only confirmation');
180
+ assert.equal(loadSettings(cwd).timeout, 42, 'saved project value applies');
181
+
182
+ result = saveSettings(
183
+ { ...DEFAULT_SETTINGS, projectScope: true, timeout: 30 },
184
+ 'project',
185
+ freshCwd
186
+ );
187
+ assert.equal(result.created, true, 'fresh project file reports created=true');
188
+ assert.equal(JSON.parse(fs.readFileSync(projectConfigFile(freshCwd), 'utf8')).projectScope, true);
189
+ assert.equal(loadSettings(freshCwd).timeout, 30, 'fresh project activates independently');
190
+ assert.equal(loadSettings(cwd).timeout, 42, 'fresh project does not alter another workspace');
191
+
192
+ // --- parked values and deactivation -----------------------------------
193
+ const parked = loadProjectFileValues(cwd);
194
+ assert.equal(parked.timeout, 42, 'parked project timeout is readable');
195
+ assert.equal(
196
+ parked.confirmProjectAgents,
197
+ undefined,
198
+ 'parked project values exclude confirmation'
199
+ );
200
+ const deactivated = deactivateProjectScope(cwd);
201
+ assert.equal(deactivated.changed, true, 'active project deactivation reports a change');
202
+ const dormantRaw = JSON.parse(fs.readFileSync(projectFile, 'utf8'));
203
+ assert.equal(dormantRaw.projectScope, false, 'deactivation writes false');
204
+ assert.ok(fs.existsSync(projectFile), 'deactivation does not delete the file');
205
+ assert.equal(loadSettings(cwd).projectScope, false, 'deactivation restores user scope');
206
+ assert.equal(loadSettings(cwd).timeout, 25, 'deactivation restores user values');
207
+ assert.equal(deactivateProjectScope(cwd).changed, false, 'already-false deactivation is a no-op');
208
+
209
+ // Keyless and legacy objects normalize safely when explicitly deactivated.
210
+ fs.writeFileSync(projectFile, JSON.stringify({ timeout: 9 }));
211
+ assert.equal(
212
+ deactivateProjectScope(cwd).changed,
213
+ true,
214
+ 'keyless object is normalized on deactivation'
215
+ );
216
+ assert.equal(JSON.parse(fs.readFileSync(projectFile, 'utf8')).projectScope, false);
217
+ fs.writeFileSync(projectFile, JSON.stringify({ settingsScope: 'project', timeout: 9 }));
218
+ assert.equal(
219
+ deactivateProjectScope(cwd).changed,
220
+ true,
221
+ 'legacy object is normalized on deactivation'
222
+ );
223
+ const normalizedLegacy = JSON.parse(fs.readFileSync(projectFile, 'utf8'));
224
+ assert.equal(normalizedLegacy.projectScope, false);
225
+ assert.ok(!('settingsScope' in normalizedLegacy), 'legacy key is removed on deactivation');
226
+ assert.equal(
227
+ deactivateProjectScope(path.join(home, 'missing')).changed,
228
+ false,
229
+ 'missing file deactivation is a no-op'
230
+ );
231
+
232
+ // --- fieldnotes session snapshot uses effective workspace settings -------
233
+ saveSettings({ ...user, fieldnotes: false }, 'user');
234
+ fs.writeFileSync(projectFile, JSON.stringify({ projectScope: true, fieldnotes: true }));
235
+ initializeSessionSettings(cwd);
236
+ assert.equal(fieldnotesEnabled(), true, 'active project fieldnotes are snapshotted');
237
+ fs.rmSync(projectFile);
238
+ initializeSessionSettings(cwd);
239
+ assert.equal(fieldnotesEnabled(), false, 'user fieldnotes are snapshotted without project file');
240
+
241
+ // --- user settings.json migration remains intact ----------------------
242
+ fs.rmSync(userConfigFile(), { force: true });
243
+ fs.rmSync(legacyFile, { force: true });
244
+ fs.writeFileSync(legacyFile, JSON.stringify({ agentScope: 'both', timeout: 25 }));
245
+ assert.equal(loadSettings().agentScope, 'both', 'legacy user file is migrated');
246
+ assert.equal(loadSettings().timeout, 25, 'legacy timeout survives migration');
247
+ assert.ok(fs.existsSync(userConfigFile()), 'new config file exists after migration');
248
+ assert.ok(!fs.existsSync(legacyFile), 'legacy user file is renamed away');
249
+
250
+ fs.writeFileSync(userConfigFile(), JSON.stringify({ timeout: 7 }));
251
+ fs.writeFileSync(legacyFile, JSON.stringify({ timeout: 99 }));
252
+ assert.equal(loadSettings().timeout, 7, 'new config wins when both files exist');
253
+ assert.ok(fs.existsSync(legacyFile), 'legacy file remains when new file exists');
254
+
255
+ console.log('All settings assertions passed.');
256
+ } finally {
257
+ if (previousAgentDir === undefined) delete process.env.PI_CODING_AGENT_DIR;
258
+ else process.env.PI_CODING_AGENT_DIR = previousAgentDir;
259
+ fs.rmSync(home, { recursive: true, force: true });
260
+ }