owenloop 0.4.0 → 0.5.0

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 (155) hide show
  1. package/CHANGELOG.md +45 -0
  2. package/README.md +98 -25
  3. package/bin/owenloop.mjs +2 -2
  4. package/dist/packages/work/src/agent/brief.d.ts +172 -0
  5. package/dist/packages/work/src/agent/brief.js +193 -0
  6. package/dist/packages/work/src/agent/loop.d.ts +135 -0
  7. package/dist/packages/work/src/agent/loop.js +542 -0
  8. package/dist/packages/work/src/agent/workdir.d.ts +210 -0
  9. package/dist/packages/work/src/agent/workdir.js +319 -0
  10. package/dist/packages/work/src/bundle/cache.d.ts +90 -0
  11. package/dist/packages/work/src/bundle/cache.js +324 -0
  12. package/dist/packages/work/src/bundle/fetch.d.ts +85 -0
  13. package/dist/packages/work/src/bundle/fetch.js +325 -0
  14. package/dist/packages/work/src/bundle/types.d.ts +160 -0
  15. package/dist/packages/work/src/bundle/types.js +1 -0
  16. package/dist/packages/work/src/credentials/owenloop.d.ts +11 -0
  17. package/dist/packages/work/src/credentials/owenloop.js +28 -0
  18. package/dist/packages/work/src/credentials/reader.d.ts +36 -0
  19. package/dist/packages/work/src/credentials/reader.js +32 -0
  20. package/dist/packages/work/src/credentials/resolve.d.ts +19 -0
  21. package/dist/packages/work/src/credentials/resolve.js +56 -0
  22. package/dist/packages/work/src/exec/loop.d.ts +29 -0
  23. package/dist/packages/work/src/exec/loop.js +215 -0
  24. package/dist/packages/work/src/exec/receipt.d.ts +38 -0
  25. package/dist/packages/work/src/exec/receipt.js +21 -0
  26. package/dist/packages/work/src/exec/runner.d.ts +65 -0
  27. package/dist/packages/work/src/exec/runner.js +185 -0
  28. package/dist/packages/work/src/harness/child-env.d.ts +100 -0
  29. package/dist/packages/work/src/harness/child-env.js +127 -0
  30. package/dist/packages/work/src/harness/claude.d.ts +128 -0
  31. package/dist/packages/work/src/harness/claude.js +635 -0
  32. package/dist/packages/work/src/harness/codex.d.ts +110 -0
  33. package/dist/packages/work/src/harness/codex.js +896 -0
  34. package/dist/packages/work/src/harness/contract.d.ts +283 -0
  35. package/dist/packages/work/src/harness/contract.js +32 -0
  36. package/dist/packages/work/src/harness/fake.d.ts +59 -0
  37. package/dist/packages/work/src/harness/fake.js +90 -0
  38. package/dist/packages/work/src/harness/jsonrpc-stdio.d.ts +108 -0
  39. package/dist/packages/work/src/harness/jsonrpc-stdio.js +344 -0
  40. package/dist/packages/work/src/harness/permissions.d.ts +62 -0
  41. package/dist/packages/work/src/harness/permissions.js +93 -0
  42. package/dist/packages/work/src/harness/registry.d.ts +47 -0
  43. package/dist/packages/work/src/harness/registry.js +45 -0
  44. package/dist/packages/work/src/harness/session-store.d.ts +163 -0
  45. package/dist/packages/work/src/harness/session-store.js +319 -0
  46. package/dist/packages/work/src/harness/types.d.ts +29 -0
  47. package/dist/packages/work/src/harness/types.js +14 -0
  48. package/dist/packages/work/src/harnesses.d.ts +38 -0
  49. package/dist/packages/work/src/harnesses.js +38 -0
  50. package/dist/packages/work/src/hold/loop.d.ts +36 -0
  51. package/dist/packages/work/src/hold/loop.js +23 -0
  52. package/dist/packages/work/src/hold/mcp.d.ts +55 -0
  53. package/dist/packages/work/src/hold/mcp.js +149 -0
  54. package/dist/packages/work/src/hub/client.d.ts +22 -0
  55. package/dist/packages/work/src/hub/client.js +78 -0
  56. package/dist/packages/work/src/hub/types.d.ts +290 -0
  57. package/dist/packages/work/src/hub/types.js +28 -0
  58. package/dist/packages/work/src/lease/loop.d.ts +94 -0
  59. package/dist/packages/work/src/lease/loop.js +277 -0
  60. package/dist/packages/work/src/main.d.ts +1 -0
  61. package/dist/packages/work/src/main.js +48 -0
  62. package/dist/packages/work/src/mcp/server.d.ts +125 -0
  63. package/dist/packages/work/src/mcp/server.js +320 -0
  64. package/dist/packages/work/src/roles/agent-run.d.ts +118 -0
  65. package/dist/packages/work/src/roles/agent-run.js +447 -0
  66. package/dist/packages/work/src/roles/exec.d.ts +40 -0
  67. package/dist/packages/work/src/roles/exec.js +203 -0
  68. package/dist/packages/work/src/roles/hold.d.ts +68 -0
  69. package/dist/packages/work/src/roles/hold.js +324 -0
  70. package/dist/packages/work/src/roles/join.d.ts +18 -0
  71. package/dist/packages/work/src/roles/join.js +204 -0
  72. package/dist/packages/work/src/roles/lint.d.ts +59 -0
  73. package/dist/packages/work/src/roles/lint.js +200 -0
  74. package/dist/packages/work/src/roles/prepare.d.ts +1 -0
  75. package/dist/packages/work/src/roles/prepare.js +249 -0
  76. package/dist/packages/work/src/roles/release.d.ts +48 -0
  77. package/dist/packages/work/src/roles/release.js +137 -0
  78. package/dist/packages/work/src/roles/sessions.d.ts +61 -0
  79. package/dist/packages/work/src/roles/sessions.js +180 -0
  80. package/dist/packages/work/src/roles/settings.d.ts +6 -0
  81. package/dist/packages/work/src/roles/settings.js +66 -0
  82. package/dist/packages/work/src/roles/shift.d.ts +12 -0
  83. package/dist/packages/work/src/roles/shift.js +228 -0
  84. package/dist/packages/work/src/roles/signals.d.ts +55 -0
  85. package/dist/packages/work/src/roles/signals.js +62 -0
  86. package/dist/packages/work/src/settings/provision.d.ts +21 -0
  87. package/dist/packages/work/src/settings/provision.js +47 -0
  88. package/dist/packages/work/src/settings/settings.d.ts +120 -0
  89. package/dist/packages/work/src/settings/settings.js +116 -0
  90. package/dist/packages/work/src/shift/client.d.ts +24 -0
  91. package/dist/packages/work/src/shift/client.js +124 -0
  92. package/dist/packages/work/src/shift/loop.d.ts +120 -0
  93. package/dist/packages/work/src/shift/loop.js +468 -0
  94. package/dist/packages/work/src/shift/protocol.d.ts +91 -0
  95. package/dist/packages/work/src/shift/protocol.js +24 -0
  96. package/dist/packages/work/src/shift/routing.d.ts +35 -0
  97. package/dist/packages/work/src/shift/routing.js +50 -0
  98. package/dist/packages/work/src/shift/runtime.d.ts +43 -0
  99. package/dist/packages/work/src/shift/runtime.js +274 -0
  100. package/dist/packages/work/src/shift/server.d.ts +23 -0
  101. package/dist/packages/work/src/shift/server.js +716 -0
  102. package/dist/packages/work/src/shift/spawn.d.ts +86 -0
  103. package/dist/packages/work/src/shift/spawn.js +100 -0
  104. package/dist/packages/work/src/shift/state.d.ts +77 -0
  105. package/dist/packages/work/src/shift/state.js +162 -0
  106. package/dist/packages/work/src/usage.d.ts +6 -0
  107. package/dist/packages/work/src/usage.js +175 -0
  108. package/dist/{add.d.ts → src/add.d.ts} +12 -40
  109. package/dist/{add.js → src/add.js} +11 -176
  110. package/dist/src/cli.d.ts +147 -0
  111. package/dist/{cli.js → src/cli.js} +1643 -353
  112. package/dist/src/credentials.d.ts +280 -0
  113. package/dist/src/credentials.js +697 -0
  114. package/dist/{defs.js → src/defs.js} +59 -36
  115. package/dist/{engine.d.ts → src/engine.d.ts} +8 -8
  116. package/dist/{engine.js → src/engine.js} +29 -20
  117. package/dist/{hub.d.ts → src/hub.d.ts} +330 -2
  118. package/dist/{hub.js → src/hub.js} +531 -1
  119. package/dist/{index.d.ts → src/index.d.ts} +3 -1
  120. package/dist/{index.js → src/index.js} +2 -1
  121. package/dist/src/lock.d.ts +80 -0
  122. package/dist/src/lock.js +217 -0
  123. package/dist/src/mcp/serve.d.ts +85 -0
  124. package/dist/src/mcp/serve.js +702 -0
  125. package/dist/src/mcp/server.d.ts +132 -0
  126. package/dist/src/mcp/server.js +327 -0
  127. package/dist/{model.d.ts → src/model.d.ts} +59 -4
  128. package/dist/{model.js → src/model.js} +149 -22
  129. package/dist/{types.d.ts → src/types.d.ts} +66 -24
  130. package/dist/{util.d.ts → src/util.d.ts} +25 -0
  131. package/dist/{util.js → src/util.js} +26 -0
  132. package/dist/src/work-settings.d.ts +57 -0
  133. package/dist/src/work-settings.js +84 -0
  134. package/docs/authoring.md +102 -53
  135. package/docs/cli.md +883 -29
  136. package/docs/design.md +119 -45
  137. package/docs/embedding.md +39 -14
  138. package/examples/workflows/{command-worker.yaml → command-executor.yaml} +15 -15
  139. package/examples/workflows/compile-dev-playbook.yaml +338 -0
  140. package/examples/workflows/judges/gate-sharpness.md +39 -0
  141. package/examples/workflows/judges/security.md +34 -0
  142. package/package.json +17 -8
  143. package/dist/cli.d.ts +0 -83
  144. /package/dist/{defs.d.ts → src/defs.d.ts} +0 -0
  145. /package/dist/{factory.d.ts → src/factory.d.ts} +0 -0
  146. /package/dist/{factory.js → src/factory.js} +0 -0
  147. /package/dist/{paths.d.ts → src/paths.d.ts} +0 -0
  148. /package/dist/{paths.js → src/paths.js} +0 -0
  149. /package/dist/{schema.d.ts → src/schema.d.ts} +0 -0
  150. /package/dist/{schema.js → src/schema.js} +0 -0
  151. /package/dist/{store.d.ts → src/store.d.ts} +0 -0
  152. /package/dist/{store.js → src/store.js} +0 -0
  153. /package/dist/{types.js → src/types.js} +0 -0
  154. /package/dist/{untar.d.ts → src/untar.d.ts} +0 -0
  155. /package/dist/{untar.js → src/untar.js} +0 -0
@@ -0,0 +1,66 @@
1
+ /**
2
+ * `owenloop work settings` — print the resolved settings file: its path, whether it
3
+ * exists, each known knob with its value and provenance, and any unrecognized
4
+ * keys (likely typos). Read-only; there is no write/edit form in v1.
5
+ *
6
+ * This reflects what the FILE supplies — the lowest-precedence tier. It does
7
+ * NOT resolve CLI flags or env vars (those belong to the individual roles at
8
+ * run time); a knob absent from the file prints its built-in default (where one
9
+ * exists) or `unset`.
10
+ *
11
+ * Exit codes: 0 when the settings are valid (including no file at all) · 1 when
12
+ * the file is malformed JSON or a known key has the wrong type · 2 on stray
13
+ * args (there are no options in v1).
14
+ */
15
+ import { inspectSettings, KNOWN_SETTINGS_KEYS } from "../settings/settings.js";
16
+ /** Built-in defaults shown for knobs absent from the file (else `unset`). */
17
+ const DEFAULT_NOTE = {
18
+ dispatchCap: '3',
19
+ commandRouting: 'shift',
20
+ };
21
+ function errMsg(err) {
22
+ return err instanceof Error ? err.message : String(err);
23
+ }
24
+ export async function run(args, deps = {}) {
25
+ const out = deps.out ?? ((line) => void process.stdout.write(`${line}\n`));
26
+ const err = deps.err ?? ((line) => void process.stderr.write(`${line}\n`));
27
+ const env = deps.env ?? process.env;
28
+ if (args.length > 0) {
29
+ err(`owenloop work settings: unexpected argument '${args[0]}'`);
30
+ err('usage: owenloop work settings');
31
+ return 2;
32
+ }
33
+ let inspection;
34
+ try {
35
+ inspection = inspectSettings(env);
36
+ }
37
+ catch (e) {
38
+ err(`owenloop work settings: ${errMsg(e)}`);
39
+ return 1;
40
+ }
41
+ const { path, exists, settings, unrecognized } = inspection;
42
+ out(`settings file: ${path}`);
43
+ out(`exists: ${exists ? 'yes' : 'no'}`);
44
+ out('');
45
+ for (const key of KNOWN_SETTINGS_KEYS) {
46
+ const value = settings[key];
47
+ if (value !== undefined) {
48
+ out(` ${key} = ${formatValue(value)} (settings)`);
49
+ }
50
+ else if (DEFAULT_NOTE[key] !== undefined) {
51
+ out(` ${key} = ${DEFAULT_NOTE[key]} (default)`);
52
+ }
53
+ else {
54
+ out(` ${key} = (unset)`);
55
+ }
56
+ }
57
+ if (unrecognized.length > 0) {
58
+ out('');
59
+ out(`unrecognized keys (ignored — likely typos): ${unrecognized.join(', ')}`);
60
+ }
61
+ return 0;
62
+ }
63
+ /** Render a settings value for display: strings bare, everything else JSON. */
64
+ function formatValue(value) {
65
+ return typeof value === 'string' ? value : JSON.stringify(value);
66
+ }
@@ -0,0 +1,12 @@
1
+ import { type ParsedArgs } from '../shift/runtime.ts';
2
+ interface StartArgs extends ParsedArgs {
3
+ all?: boolean;
4
+ crews: string[];
5
+ }
6
+ declare function parseStartArgs(args: string[]): StartArgs;
7
+ declare function resolveSocketPath(flag: string | undefined): {
8
+ path?: string;
9
+ error?: string;
10
+ };
11
+ export declare function run(args: string[]): Promise<number>;
12
+ export { parseStartArgs, resolveSocketPath };
@@ -0,0 +1,228 @@
1
+ /**
2
+ * Public `owenloop shift start|next|status|end` command surface.
3
+ *
4
+ * `start` delegates all origin, credential, settings, cache, spawner, and loop
5
+ * construction to the shift runtime. `next`, `status`, and `end` are thin local
6
+ * socket clients and never contact the hub directly.
7
+ */
8
+ import { loadSettings } from "../settings/settings.js";
9
+ import { resolveStateDir } from "../shift/state.js";
10
+ import { resolveStateDirOverride, runShiftRuntime } from "../shift/runtime.js";
11
+ import { noDaemonMessage, parseNextArgs, parseStateDirArgs, requestShift, ShiftClientError, shiftSocketPath, } from "../shift/client.js";
12
+ import { isShiftError } from "../shift/protocol.js";
13
+ function usage() {
14
+ process.stderr.write('usage: owenloop shift start <crew...> [--all] [--origin <url>] [--as <account>] [--name <n>]\n' +
15
+ ' [--cap <n>] [--max-agents <n>] [--poll-interval <ms>] [--once]\n' +
16
+ ' [--cache-dir <p>] [--state-dir <p>]\n' +
17
+ ' owenloop shift next [--wait <seconds>] [--state-dir <p>]\n' +
18
+ ' owenloop shift status [--state-dir <p>]\n' +
19
+ ' owenloop shift end [--state-dir <p>]\n');
20
+ }
21
+ function intValue(raw, flag) {
22
+ const value = Number(raw);
23
+ if (!Number.isFinite(value) || !Number.isInteger(value) || value < 0) {
24
+ return `${flag} must be a non-negative integer, got '${raw}'`;
25
+ }
26
+ return value;
27
+ }
28
+ function parseStartArgs(args) {
29
+ const parsed = { crews: [] };
30
+ const valueFlags = new Set(['--origin', '--as', '--name', '--cap', '--max-agents', '--poll-interval', '--cache-dir', '--state-dir']);
31
+ for (let i = 0; i < args.length; i++) {
32
+ const raw = args[i];
33
+ const name = raw.startsWith('--') && raw.includes('=') ? raw.slice(0, raw.indexOf('=')) : raw;
34
+ if (name === '--all') {
35
+ parsed.all = true;
36
+ continue;
37
+ }
38
+ if (name === '--once') {
39
+ parsed.once = true;
40
+ continue;
41
+ }
42
+ if (valueFlags.has(name)) {
43
+ const eq = raw.indexOf('=');
44
+ const value = eq !== -1 ? raw.slice(eq + 1) : args[++i];
45
+ if (value === undefined || value.trim() === '')
46
+ return { crews: parsed.crews, error: `missing value for ${name}` };
47
+ if (name === '--origin')
48
+ parsed.origin = value;
49
+ else if (name === '--as')
50
+ parsed.as = value;
51
+ else if (name === '--name') {
52
+ if (value.trim() === '')
53
+ return { crews: parsed.crews, error: '--name requires a non-empty value' };
54
+ parsed.name = value;
55
+ }
56
+ else if (name === '--cache-dir')
57
+ parsed.cacheDir = value;
58
+ else if (name === '--state-dir')
59
+ parsed.stateDir = value;
60
+ else if (name === '--cap') {
61
+ const n = intValue(value, '--cap');
62
+ if (typeof n !== 'number')
63
+ return { crews: parsed.crews, error: n };
64
+ parsed.cap = n;
65
+ }
66
+ else if (name === '--max-agents') {
67
+ const n = intValue(value, '--max-agents');
68
+ if (typeof n !== 'number')
69
+ return { crews: parsed.crews, error: n };
70
+ parsed.maxAgents = n;
71
+ }
72
+ else if (name === '--poll-interval') {
73
+ const n = intValue(value, '--poll-interval');
74
+ if (typeof n !== 'number')
75
+ return { crews: parsed.crews, error: n };
76
+ parsed.pollIntervalMs = n;
77
+ }
78
+ continue;
79
+ }
80
+ if (raw.startsWith('-'))
81
+ return { crews: parsed.crews, error: `unknown option '${raw}'` };
82
+ const crew = raw.trim();
83
+ if (crew !== '' && !parsed.crews.includes(crew))
84
+ parsed.crews.push(crew);
85
+ }
86
+ if (parsed.all === true && parsed.crews.length > 0) {
87
+ return { crews: parsed.crews, error: '--all cannot be combined with named crews' };
88
+ }
89
+ if (parsed.all !== true && parsed.crews.length === 0) {
90
+ return { crews: parsed.crews, error: 'name at least one crew or pass --all to serve every crew' };
91
+ }
92
+ parsed.serveCrews = parsed.all === true ? [] : parsed.crews;
93
+ return parsed;
94
+ }
95
+ function resolveSocketPath(flag) {
96
+ const env = process.env;
97
+ let settingsStateDir;
98
+ if (flag === undefined && (env['OWENLOOP_STATE_DIR'] === undefined || env['OWENLOOP_STATE_DIR']?.trim() === '')) {
99
+ try {
100
+ settingsStateDir = loadSettings(env).stateDir;
101
+ }
102
+ catch (error) {
103
+ return { error: error instanceof Error ? error.message : String(error) };
104
+ }
105
+ }
106
+ try {
107
+ const stateDir = resolveStateDir(env, resolveStateDirOverride(flag, env, settingsStateDir));
108
+ return { path: shiftSocketPath(stateDir) };
109
+ }
110
+ catch (error) {
111
+ return { error: error instanceof Error ? error.message : String(error) };
112
+ }
113
+ }
114
+ function printJson(value) {
115
+ process.stdout.write(`${JSON.stringify(value)}\n`);
116
+ }
117
+ async function runNext(args) {
118
+ const parsed = parseNextArgs(args);
119
+ if (parsed.error !== undefined) {
120
+ process.stderr.write(`owenloop shift next: ${parsed.error}\n`);
121
+ usage();
122
+ return 2;
123
+ }
124
+ const socket = resolveSocketPath(parsed.stateDir);
125
+ if (socket.error !== undefined || socket.path === undefined) {
126
+ process.stderr.write(`owenloop shift next: ${socket.error ?? 'cannot resolve state directory'}\n`);
127
+ return 1;
128
+ }
129
+ try {
130
+ const response = await requestShift(socket.path, { op: 'next', wait_ms: parsed.waitMs });
131
+ if (isShiftError(response)) {
132
+ process.stderr.write(`${response.error}\n`);
133
+ return 1;
134
+ }
135
+ printJson(response);
136
+ return 0;
137
+ }
138
+ catch (error) {
139
+ process.stderr.write(`${error instanceof Error ? error.message : String(error)}\n`);
140
+ return 1;
141
+ }
142
+ }
143
+ async function runStatus(args) {
144
+ const parsed = parseStateDirArgs(args);
145
+ if (parsed.error !== undefined) {
146
+ process.stderr.write(`owenloop shift status: ${parsed.error}\n`);
147
+ usage();
148
+ return 2;
149
+ }
150
+ const socket = resolveSocketPath(parsed.stateDir);
151
+ if (socket.error !== undefined || socket.path === undefined) {
152
+ process.stderr.write(`owenloop shift status: ${socket.error ?? 'cannot resolve state directory'}\n`);
153
+ return 1;
154
+ }
155
+ try {
156
+ const response = await requestShift(socket.path, { op: 'status' });
157
+ if (isShiftError(response)) {
158
+ process.stderr.write(`${response.error}\n`);
159
+ return 1;
160
+ }
161
+ printJson(response);
162
+ return 0;
163
+ }
164
+ catch (error) {
165
+ if (error instanceof ShiftClientError && error.absent) {
166
+ printJson({ status: 'no daemon', socket: socket.path });
167
+ return 0;
168
+ }
169
+ process.stderr.write(`${error instanceof Error ? error.message : String(error)}\n`);
170
+ return 1;
171
+ }
172
+ }
173
+ async function runEnd(args) {
174
+ const parsed = parseStateDirArgs(args);
175
+ if (parsed.error !== undefined) {
176
+ process.stderr.write(`owenloop shift end: ${parsed.error}\n`);
177
+ usage();
178
+ return 2;
179
+ }
180
+ const socket = resolveSocketPath(parsed.stateDir);
181
+ if (socket.error !== undefined || socket.path === undefined) {
182
+ process.stderr.write(`owenloop shift end: ${socket.error ?? 'cannot resolve state directory'}\n`);
183
+ return 1;
184
+ }
185
+ try {
186
+ const response = await requestShift(socket.path, { op: 'end' });
187
+ if (isShiftError(response)) {
188
+ process.stderr.write(`${response.error}\n`);
189
+ return 1;
190
+ }
191
+ printJson(response);
192
+ return 0;
193
+ }
194
+ catch (error) {
195
+ if (error instanceof ShiftClientError && error.absent) {
196
+ process.stderr.write(`${noDaemonMessage(socket.path)}\n`);
197
+ return 1;
198
+ }
199
+ process.stderr.write(`${error instanceof Error ? error.message : String(error)}\n`);
200
+ return 1;
201
+ }
202
+ }
203
+ export async function run(args) {
204
+ const [command, ...rest] = args;
205
+ if (command === undefined || command === '--help' || command === '-h' || command === 'help') {
206
+ usage();
207
+ return command === undefined ? 2 : 0;
208
+ }
209
+ if (command === 'start') {
210
+ const parsed = parseStartArgs(rest);
211
+ if (parsed.error !== undefined) {
212
+ process.stderr.write(`owenloop shift start: ${parsed.error}\n`);
213
+ usage();
214
+ return 2;
215
+ }
216
+ return runShiftRuntime(parsed, { daemon: true, role: 'shift' });
217
+ }
218
+ if (command === 'next')
219
+ return runNext(rest);
220
+ if (command === 'status')
221
+ return runStatus(rest);
222
+ if (command === 'end')
223
+ return runEnd(rest);
224
+ process.stderr.write(`owenloop shift: unknown command '${command}'\n`);
225
+ usage();
226
+ return 2;
227
+ }
228
+ export { parseStartArgs, resolveSocketPath };
@@ -0,0 +1,55 @@
1
+ /**
2
+ * Process-lifecycle signal seams shared by the standing roles (`shift`, `hold`).
3
+ *
4
+ * Extracted from `src/roles/shift.ts` (C3) so C4's `hold` reuses the exact
5
+ * same shutdown mechanism instead of inventing a second one. Two seams:
6
+ *
7
+ * - `installSignalHandlers` — first SIGINT/SIGTERM flips the target's
8
+ * `stop(reason?)`; a second signal (either kind) hard-exits 130 (an
9
+ * operator insisting). The role name and the first-signal drain note are
10
+ * parameterized so each role prints its own line; shift's defaults keep its
11
+ * messages byte-identical to C3 (its regression test asserts them).
12
+ * - `watchStdinEof` — fires a callback once when stdin reaches EOF (`end` or
13
+ * `close`). For `hold`, stdin EOF is the parent-session-death signal (a live
14
+ * pipe closing means the interactive session that spawned hold is gone), so
15
+ * it triggers the same final-breath handoff a signal does.
16
+ *
17
+ * Both take injectable hosts (a `process`-shaped slice / a stream-shaped slice)
18
+ * so the wiring is testable without signaling the real process or closing real
19
+ * stdin.
20
+ */
21
+ /** The slice of `process` the signal wiring needs — injectable for tests. */
22
+ export interface SignalHost {
23
+ on(signal: 'SIGINT' | 'SIGTERM', handler: () => void): unknown;
24
+ exit(code: number): void;
25
+ }
26
+ /** Message/behavior knobs for a role's signal wiring. */
27
+ export interface SignalOptions {
28
+ /** Role name for the message prefix `owenloop work <role>:` (default `shift`). */
29
+ role?: string;
30
+ /** First-signal note after `<sig> received — ` (default shift's drain note). */
31
+ drainNote?: string;
32
+ /** Reason handed to `target.stop()` on the first signal (roles that care). */
33
+ stopReason?: string;
34
+ }
35
+ /**
36
+ * Clean-shutdown signal wiring: the first SIGINT/SIGTERM flips
37
+ * `target.stop(reason)`; a second signal hard-exits 130. Exported with an
38
+ * injectable host so the wiring is testable without signaling the test process.
39
+ */
40
+ export declare function installSignalHandlers(target: {
41
+ stop(reason?: string): void;
42
+ }, host: SignalHost, err: (line: string) => void, opts?: SignalOptions): void;
43
+ /** The slice of a readable stream the EOF watcher needs — injectable for tests. */
44
+ export interface StdinHost {
45
+ on(event: 'end' | 'close', handler: () => void): unknown;
46
+ /** Flowing mode is required for `end` to fire on a piped stdin; optional. */
47
+ resume?(): void;
48
+ }
49
+ /**
50
+ * Fire `cb` exactly once when the stream reaches EOF (`end` or `close`,
51
+ * whichever comes first). Calls `resume()` if present so a paused stdin starts
52
+ * flowing (otherwise `end` never arrives). Idempotent — a stream that emits
53
+ * both `end` and `close` still calls back once.
54
+ */
55
+ export declare function watchStdinEof(stream: StdinHost, cb: () => void): void;
@@ -0,0 +1,62 @@
1
+ /**
2
+ * Process-lifecycle signal seams shared by the standing roles (`shift`, `hold`).
3
+ *
4
+ * Extracted from `src/roles/shift.ts` (C3) so C4's `hold` reuses the exact
5
+ * same shutdown mechanism instead of inventing a second one. Two seams:
6
+ *
7
+ * - `installSignalHandlers` — first SIGINT/SIGTERM flips the target's
8
+ * `stop(reason?)`; a second signal (either kind) hard-exits 130 (an
9
+ * operator insisting). The role name and the first-signal drain note are
10
+ * parameterized so each role prints its own line; shift's defaults keep its
11
+ * messages byte-identical to C3 (its regression test asserts them).
12
+ * - `watchStdinEof` — fires a callback once when stdin reaches EOF (`end` or
13
+ * `close`). For `hold`, stdin EOF is the parent-session-death signal (a live
14
+ * pipe closing means the interactive session that spawned hold is gone), so
15
+ * it triggers the same final-breath handoff a signal does.
16
+ *
17
+ * Both take injectable hosts (a `process`-shaped slice / a stream-shaped slice)
18
+ * so the wiring is testable without signaling the real process or closing real
19
+ * stdin.
20
+ */
21
+ const DEFAULT_ROLE = 'shift';
22
+ const DEFAULT_DRAIN_NOTE = 'draining, in-flight children keep running';
23
+ /**
24
+ * Clean-shutdown signal wiring: the first SIGINT/SIGTERM flips
25
+ * `target.stop(reason)`; a second signal hard-exits 130. Exported with an
26
+ * injectable host so the wiring is testable without signaling the test process.
27
+ */
28
+ export function installSignalHandlers(target, host, err, opts = {}) {
29
+ const role = opts.role ?? DEFAULT_ROLE;
30
+ const drainNote = opts.drainNote ?? DEFAULT_DRAIN_NOTE;
31
+ let signalled = false;
32
+ const onSignal = (sig) => {
33
+ if (signalled) {
34
+ err(`owenloop work ${role}: second ${sig} — exiting now`);
35
+ host.exit(130);
36
+ return;
37
+ }
38
+ signalled = true;
39
+ err(`owenloop work ${role}: ${sig} received — ${drainNote}`);
40
+ target.stop(opts.stopReason);
41
+ };
42
+ host.on('SIGINT', () => onSignal('SIGINT'));
43
+ host.on('SIGTERM', () => onSignal('SIGTERM'));
44
+ }
45
+ /**
46
+ * Fire `cb` exactly once when the stream reaches EOF (`end` or `close`,
47
+ * whichever comes first). Calls `resume()` if present so a paused stdin starts
48
+ * flowing (otherwise `end` never arrives). Idempotent — a stream that emits
49
+ * both `end` and `close` still calls back once.
50
+ */
51
+ export function watchStdinEof(stream, cb) {
52
+ let fired = false;
53
+ const fire = () => {
54
+ if (fired)
55
+ return;
56
+ fired = true;
57
+ cb();
58
+ };
59
+ stream.on('end', fire);
60
+ stream.on('close', fire);
61
+ stream.resume?.();
62
+ }
@@ -0,0 +1,21 @@
1
+ export type RecordHubOriginResult = {
2
+ outcome: 'written';
3
+ path: string;
4
+ } | {
5
+ outcome: 'unchanged';
6
+ path: string;
7
+ } | {
8
+ outcome: 'conflict';
9
+ path: string;
10
+ existing: string;
11
+ };
12
+ /**
13
+ * Record `origin` (already `normalizeOrigin`d by the caller) as
14
+ * `settings.hubOrigin`, first-write-wins:
15
+ * - absent/blank `hubOrigin` → merge-write `{ ...settings, hubOrigin: origin }`,
16
+ * creating the settings directory if needed. Unknown keys already in the
17
+ * file are preserved (`inspectSettings` retains them on `settings`).
18
+ * - present, normalizes equal → `unchanged`, no write (file byte-identical).
19
+ * - present, differs (or does not itself normalize) → `conflict`, no write.
20
+ */
21
+ export declare function recordHubOrigin(env: Record<string, string | undefined>, origin: string): RecordHubOriginResult;
@@ -0,0 +1,47 @@
1
+ /**
2
+ * The ONE settings writer in owenloop, provisioning-time only.
3
+ *
4
+ * `settings/settings.ts` is deliberately read-only (see its HARD RULE comment)
5
+ * — every role loads settings, no role writes them. `owenloop work join` is the sole
6
+ * exception: it is a one-time provisioning act, not a runtime write, so its
7
+ * write path lives in this separate module rather than growing a write
8
+ * function onto `settings.ts` itself.
9
+ *
10
+ * FIRST WRITE WINS: `recordHubOrigin` never overwrites a differing existing
11
+ * `hubOrigin`. A box that has already recorded a hub is not silently
12
+ * re-pointed at another one by a second `join` run; the caller (join.ts)
13
+ * surfaces a `conflict` as a non-fatal warning instead.
14
+ */
15
+ import { mkdirSync, writeFileSync } from 'node:fs';
16
+ import { dirname } from 'node:path';
17
+ import { normalizeOrigin } from "../../../../src/hub.js";
18
+ import { inspectSettings, settingsPath } from "./settings.js";
19
+ /**
20
+ * Record `origin` (already `normalizeOrigin`d by the caller) as
21
+ * `settings.hubOrigin`, first-write-wins:
22
+ * - absent/blank `hubOrigin` → merge-write `{ ...settings, hubOrigin: origin }`,
23
+ * creating the settings directory if needed. Unknown keys already in the
24
+ * file are preserved (`inspectSettings` retains them on `settings`).
25
+ * - present, normalizes equal → `unchanged`, no write (file byte-identical).
26
+ * - present, differs (or does not itself normalize) → `conflict`, no write.
27
+ */
28
+ export function recordHubOrigin(env, origin) {
29
+ const path = settingsPath(env);
30
+ const { settings } = inspectSettings(env);
31
+ const existing = settings.hubOrigin;
32
+ if (existing === undefined || existing.trim() === '') {
33
+ mkdirSync(dirname(path), { recursive: true });
34
+ writeFileSync(path, `${JSON.stringify({ ...settings, hubOrigin: origin }, null, 2)}\n`);
35
+ return { outcome: 'written', path };
36
+ }
37
+ let normalizedExisting;
38
+ try {
39
+ normalizedExisting = normalizeOrigin(existing);
40
+ }
41
+ catch {
42
+ return { outcome: 'conflict', path, existing };
43
+ }
44
+ if (normalizedExisting === origin)
45
+ return { outcome: 'unchanged', path };
46
+ return { outcome: 'conflict', path, existing };
47
+ }
@@ -0,0 +1,120 @@
1
+ /**
2
+ * The settings surface — every knob optional, a missing file loading as `{}`.
3
+ * Each field is the lowest-precedence fallback for a role option (a CLI flag
4
+ * or env var always wins over it):
5
+ * - `hubOrigin` — default hub origin when `--origin` is omitted
6
+ * (prepare, shift, hold, exec, release).
7
+ * - `cacheDir` — bundle cache root; overrides the XDG default
8
+ * (see bundle/cache.ts).
9
+ * - `stateDir` — shift in-flight state dir; overrides the XDG default
10
+ * (below `OWENLOOP_STATE_DIR`).
11
+ * - `dispatchCap` — shift max in-flight exec children; below `--cap`,
12
+ * above the built-in default of 3. A positive integer.
13
+ * - `commandRouting` — who runs `executor: 'command'` steps this machine sees.
14
+ */
15
+ export interface Settings {
16
+ /** Default hub origin when `--origin` is omitted. */
17
+ hubOrigin?: string;
18
+ /** Bundle cache root; overrides the XDG default (see bundle/cache.ts). */
19
+ cacheDir?: string;
20
+ /** Shift in-flight state dir; fallback below `--state-dir`/env. */
21
+ stateDir?: string;
22
+ /** Shift dispatch cap (positive integer); fallback below `--cap`, default 3. */
23
+ dispatchCap?: number;
24
+ /**
25
+ * Who runs `executor: 'command'` steps this machine sees: `'shift'` (default)
26
+ * lets the shift auto-dispatch them; `'manual'` leaves them for a human/
27
+ * session to pick up via the pickup window. The C3 shift is the only reader.
28
+ * A per-step `x.owenloop.routing` override can tighten (never loosen) this —
29
+ * most restrictive wins (see src/shift/routing.ts).
30
+ */
31
+ commandRouting?: 'shift' | 'manual';
32
+ /**
33
+ * Max in-flight `agent-run` children (positive integer, default 4 —
34
+ * `DEFAULT_MAX_AGENTS` in `src/roles/shift.ts`). A SEPARATE
35
+ * budget from `dispatchCap`, which meters `exec` children — an agent turn is
36
+ * long and memory-heavy where a command is short, so one number cannot serve
37
+ * both. Fallback below `--max-agents`.
38
+ */
39
+ maxConcurrentAgents?: number;
40
+ /**
41
+ * Phase 4 — the root under which per-RUN agent working directories live.
42
+ *
43
+ * An `agent-run` child works in `<workRoot>/<workflow>/<run>/`, created on
44
+ * first use. PER RUN, not per step: every step of a run shares one directory,
45
+ * which is what lets a downstream step read what an upstream step wrote, and
46
+ * what makes the removal gate a single question ("does this run still have an
47
+ * open order?") instead of a `consumes` walk.
48
+ *
49
+ * Default when unset: `<cacheDir>/work`. Overridden per order by
50
+ * `OrderPacket.workdir` — the hub always wins, and a hub-supplied workdir is
51
+ * NEVER removed by the reaper, which only ever removes what it created under
52
+ * `workRoot`.
53
+ *
54
+ * Pulled forward from Phase 5, which `docs/agent-runner.md` originally
55
+ * deferred it to: worktree lifetime is not implementable without a work root.
56
+ */
57
+ workRoot?: string;
58
+ /**
59
+ * Phase 4 — an optional local git repo. When set, a per-run work directory is
60
+ * created as `git worktree add` against this repo instead of a plain `mkdir`,
61
+ * and removed with `git worktree remove` instead of a plain `rm -rf`.
62
+ *
63
+ * LOCALLY OPT-IN, deliberately. Nothing in `src/bundle/types.ts` or
64
+ * `src/hub/types.ts` lets a workflow declare a repo, and adding one would be a
65
+ * hub protocol change — an explicit non-goal. So worktree mode is a property
66
+ * of the MACHINE running the shift, not of the workflow.
67
+ */
68
+ workRepo?: string;
69
+ }
70
+ /** The known settings keys, in the order `owenloop work settings` prints them. */
71
+ export declare const KNOWN_SETTINGS_KEYS: readonly ["hubOrigin", "cacheDir", "stateDir", "dispatchCap", "commandRouting", "maxConcurrentAgents", "workRoot", "workRepo"];
72
+ /**
73
+ * A validated load: the typed `settings` (unknown keys retained for forward
74
+ * compatibility — consumers ignore them), plus the list of keys that are NOT
75
+ * recognized so `owenloop work settings` can flag likely typos.
76
+ */
77
+ export interface ValidatedSettings {
78
+ settings: Settings;
79
+ /** Keys present in the file that owenloop does not recognize. */
80
+ unrecognized: string[];
81
+ }
82
+ /** The result of inspecting the settings file: where it is, whether it exists, and its validated contents. */
83
+ export interface SettingsInspection extends ValidatedSettings {
84
+ path: string;
85
+ exists: boolean;
86
+ }
87
+ /**
88
+ * Resolve the settings file path from the caller's env:
89
+ * `$XDG_CONFIG_HOME/owenloop/settings.json` when `XDG_CONFIG_HOME` is set and
90
+ * non-empty, else `$HOME/.config/owenloop/settings.json`. Throws when neither
91
+ * is available rather than guessing a home directory.
92
+ */
93
+ export declare function settingsPath(env: Record<string, string | undefined>): string;
94
+ /**
95
+ * Validate a parsed settings object. Checks the TYPE of every known key
96
+ * (throwing an actionable error naming the key, expected type, received value,
97
+ * and file path on a mismatch) and collects any unrecognized keys. Unknown
98
+ * keys are retained on the returned `settings` (forward compatible) — only
99
+ * their names are reported, never fatal.
100
+ *
101
+ * `dispatchCap` must be a positive integer; `commandRouting` must be one of the
102
+ * two literals. Any other type on a known key is a hard error.
103
+ */
104
+ export declare function validateSettings(raw: unknown, path: string): ValidatedSettings;
105
+ /**
106
+ * Inspect the settings file: resolve its path, whether it exists, and its
107
+ * validated contents. A missing file is not an error (`exists: false`,
108
+ * settings `{}`). Malformed JSON or an invalid known-key type throws a clear,
109
+ * path-named error. This is the single read+validate path that `loadSettings`
110
+ * and the `settings` print role share.
111
+ */
112
+ export declare function inspectSettings(env: Record<string, string | undefined>): SettingsInspection;
113
+ /**
114
+ * Load, parse, and validate the settings file. A missing file yields `{}` (not
115
+ * an error). Malformed JSON or an invalid known-key type throws a clear error
116
+ * rather than silently defaulting — a silent default would mask config bugs.
117
+ * Every consumer that calls `loadSettings` gets known-key type validation for
118
+ * free; unknown keys pass through untouched.
119
+ */
120
+ export declare function loadSettings(env: Record<string, string | undefined>): Settings;