owenloop 0.5.8 → 0.5.10

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 (131) hide show
  1. package/CHANGELOG.md +69 -0
  2. package/README.md +81 -39
  3. package/bin/owenloop.mjs +16 -1
  4. package/dist/packages/work/src/agent/loop.d.ts +23 -8
  5. package/dist/packages/work/src/agent/loop.js +55 -6
  6. package/dist/packages/work/src/bundle/pull.d.ts +21 -0
  7. package/dist/packages/work/src/bundle/pull.js +118 -0
  8. package/dist/packages/work/src/consumed-verifier.js +6 -17
  9. package/dist/packages/work/src/exec/instructions.d.ts +4 -1
  10. package/dist/packages/work/src/exec/instructions.js +3 -0
  11. package/dist/packages/work/src/exec/loop.d.ts +2 -2
  12. package/dist/packages/work/src/exec/loop.js +273 -46
  13. package/dist/packages/work/src/exec/receipt.d.ts +7 -7
  14. package/dist/packages/work/src/exec/receipt.js +6 -6
  15. package/dist/packages/work/src/harness/claude.js +116 -0
  16. package/dist/packages/work/src/harness/codex.d.ts +8 -0
  17. package/dist/packages/work/src/harness/codex.js +27 -1
  18. package/dist/packages/work/src/harness/contract.d.ts +9 -0
  19. package/dist/packages/work/src/hub/client.d.ts +19 -4
  20. package/dist/packages/work/src/hub/client.js +7 -3
  21. package/dist/packages/work/src/hub/types.d.ts +84 -0
  22. package/dist/packages/work/src/main.js +1 -0
  23. package/dist/packages/work/src/roles/agent-run.js +57 -32
  24. package/dist/packages/work/src/roles/exec.js +27 -8
  25. package/dist/packages/work/src/roles/settings.js +2 -0
  26. package/dist/packages/work/src/roles/shift.js +14 -2
  27. package/dist/packages/work/src/roles/util.d.ts +1 -0
  28. package/dist/packages/work/src/roles/util.js +10 -0
  29. package/dist/packages/work/src/settings/hub-roster-cache.d.ts +68 -0
  30. package/dist/packages/work/src/settings/hub-roster-cache.js +370 -0
  31. package/dist/packages/work/src/settings/roster.d.ts +84 -0
  32. package/dist/packages/work/src/settings/roster.js +364 -5
  33. package/dist/packages/work/src/settings/serving.d.ts +17 -0
  34. package/dist/packages/work/src/settings/serving.js +79 -0
  35. package/dist/packages/work/src/settings/settings.d.ts +14 -1
  36. package/dist/packages/work/src/settings/settings.js +14 -0
  37. package/dist/packages/work/src/shift/loop.d.ts +108 -5
  38. package/dist/packages/work/src/shift/loop.js +416 -54
  39. package/dist/packages/work/src/shift/protocol.d.ts +7 -5
  40. package/dist/packages/work/src/shift/runtime.d.ts +18 -0
  41. package/dist/packages/work/src/shift/runtime.js +104 -5
  42. package/dist/packages/work/src/shift/server.js +2 -0
  43. package/dist/packages/work/src/shift/spawn.d.ts +17 -2
  44. package/dist/packages/work/src/shift/spawn.js +16 -13
  45. package/dist/packages/work/src/shift/state.d.ts +29 -2
  46. package/dist/packages/work/src/shift/state.js +45 -15
  47. package/dist/packages/work/src/submit-proof.d.ts +11 -8
  48. package/dist/packages/work/src/submit-proof.js +11 -8
  49. package/dist/packages/work/src/usage.d.ts +1 -1
  50. package/dist/packages/work/src/usage.js +7 -1
  51. package/dist/packages/work/src/util/modifier-init.d.ts +7 -0
  52. package/dist/packages/work/src/util/modifier-init.js +73 -0
  53. package/dist/src/bundle/tar.d.ts +9 -4
  54. package/dist/src/bundle/tar.js +9 -4
  55. package/dist/src/capabilities.d.ts +76 -6
  56. package/dist/src/capabilities.js +49 -6
  57. package/dist/src/capability-mapping-client.d.ts +29 -0
  58. package/dist/src/capability-mapping-client.js +160 -0
  59. package/dist/src/cli.d.ts +16 -3
  60. package/dist/src/cli.js +1925 -281
  61. package/dist/src/config-dir.d.ts +1 -1
  62. package/dist/src/config-dir.js +1 -1
  63. package/dist/src/crypto/index.d.ts +1 -1
  64. package/dist/src/crypto/index.js +1 -1
  65. package/dist/src/crypto/org-root.d.ts +30 -12
  66. package/dist/src/crypto/org-root.js +162 -14
  67. package/dist/src/crypto/records.d.ts +2 -0
  68. package/dist/src/crypto/records.js +2 -0
  69. package/dist/src/defs.d.ts +38 -2
  70. package/dist/src/defs.js +593 -86
  71. package/dist/src/engine.d.ts +103 -25
  72. package/dist/src/engine.js +331 -79
  73. package/dist/src/hub.d.ts +77 -0
  74. package/dist/src/hub.js +162 -0
  75. package/dist/src/implements.d.ts +56 -0
  76. package/dist/src/implements.js +790 -0
  77. package/dist/src/index.d.ts +11 -9
  78. package/dist/src/index.js +6 -5
  79. package/dist/src/mcp/serve.d.ts +22 -0
  80. package/dist/src/mcp/serve.js +330 -41
  81. package/dist/src/mcp/server.d.ts +10 -7
  82. package/dist/src/mcp/server.js +53 -8
  83. package/dist/src/model.d.ts +48 -10
  84. package/dist/src/model.js +252 -99
  85. package/dist/src/order-resolver.d.ts +1 -0
  86. package/dist/src/order-resolver.js +8 -1
  87. package/dist/src/schemas/index.d.ts +11 -0
  88. package/dist/src/schemas/order.v1.schema.json +7 -1
  89. package/dist/src/store/def-source.d.ts +19 -0
  90. package/dist/src/store/def-source.js +87 -17
  91. package/dist/src/store/gc-recovery.d.ts +46 -0
  92. package/dist/src/store/gc-recovery.js +258 -0
  93. package/dist/src/store/gc.d.ts +94 -0
  94. package/dist/src/store/gc.js +562 -0
  95. package/dist/src/store/index.d.ts +3 -1
  96. package/dist/src/store/index.js +2 -0
  97. package/dist/src/store/install.d.ts +34 -5
  98. package/dist/src/store/install.js +73 -11
  99. package/dist/src/store/pre-commit-verifier.js +42 -2
  100. package/dist/src/store/snapshot-guard.d.ts +18 -0
  101. package/dist/src/store/snapshot-guard.js +94 -0
  102. package/dist/src/store.d.ts +69 -4
  103. package/dist/src/store.js +254 -16
  104. package/dist/src/types.d.ts +101 -20
  105. package/dist/src/util.js +4 -1
  106. package/docs/authoring.md +235 -10
  107. package/docs/bundles.md +45 -2
  108. package/docs/cli.md +437 -55
  109. package/docs/crypto.md +32 -10
  110. package/docs/design.md +177 -47
  111. package/docs/evals/mcp-charter-baseline.json +428 -0
  112. package/docs/mcp-charter-eval.md +124 -0
  113. package/docs/routing.md +189 -34
  114. package/docs/shift-logs.md +38 -9
  115. package/docs/wire-contracts.md +78 -14
  116. package/examples/workflows/compile-dev-playbook.yaml +1 -1
  117. package/examples/workflows/delivery.yaml +31 -14
  118. package/examples/workflows/ship.yaml +38 -4
  119. package/package.json +2 -1
  120. package/plugins/claude-code/plugin/.claude-plugin/plugin.json +1 -1
  121. package/plugins/claude-code/plugin/.mcp.json +1 -1
  122. package/plugins/claude-code/plugin/skills/author/SKILL.md +22 -0
  123. package/plugins/claude-code/plugin/skills/ephemeral/SKILL.md +95 -0
  124. package/plugins/claude-code/plugin/skills/graduate/SKILL.md +156 -0
  125. package/plugins/claude-code/plugin/skills/plan/SKILL.md +236 -0
  126. package/plugins/codex/plugins/owenloop/.codex-plugin/plugin.json +1 -1
  127. package/plugins/codex/plugins/owenloop/.mcp.json +1 -1
  128. package/plugins/codex/plugins/owenloop/skills/author/SKILL.md +22 -0
  129. package/plugins/codex/plugins/owenloop/skills/ephemeral/SKILL.md +95 -0
  130. package/plugins/codex/plugins/owenloop/skills/graduate/SKILL.md +156 -0
  131. package/plugins/codex/plugins/owenloop/skills/plan/SKILL.md +236 -0
@@ -109,6 +109,30 @@ export function resolveMcpOrigin(io, hubFlag) {
109
109
  }
110
110
  return DEFAULT_HUB;
111
111
  }
112
+ /** Repo-name charset — kept local so this module does not depend on the installer. */
113
+ const REPO_SEGMENT_RE = /^[A-Za-z0-9._-]+$/;
114
+ /**
115
+ * The default `scope` for a run started from inside a repo session: the repo
116
+ * name, taken from the `origin` remote's URL (last path segment, trailing
117
+ * `.git` removed). Worktree-stable by construction — every checkout of one repo
118
+ * reports the same remote, whereas the directory name differs per worktree.
119
+ *
120
+ * Returns `undefined` — meaning "send no scope at all" — for every failure:
121
+ * no runner seam, not a git repo, no `origin` remote, empty or unparseable URL,
122
+ * or a segment outside the legal charset. Never guesses a label.
123
+ */
124
+ export function resolveRepoScope(io) {
125
+ if (io.runCommand === undefined)
126
+ return undefined;
127
+ const r = io.runCommand('git', ['-C', io.cwd, 'remote', 'get-url', 'origin']);
128
+ if (r.status !== 0)
129
+ return undefined;
130
+ const url = r.stdout.trim().replace(/\/+$/, '');
131
+ if (url === '')
132
+ return undefined;
133
+ const segment = (url.split(/[/:]/).pop() ?? '').replace(/\.git$/, '');
134
+ return REPO_SEGMENT_RE.test(segment) ? segment : undefined;
135
+ }
112
136
  // ---- the authenticated hub client -------------------------------------------
113
137
  /** The non-interactive "you are not authenticated" instruction (Decision 8). */
114
138
  function loginHint(origin) {
@@ -125,8 +149,51 @@ function loginHint(origin) {
125
149
  * 4. on a 401 with an oauth credential, exactly ONE `refreshOAuth` + one
126
150
  * retry; a final 401 → `authFailed`.
127
151
  * The response body is parsed leniently (a parse failure yields `{}`, status
128
- * preserved). The bearer never leaves the `Authorization` header.
152
+ * preserved), including Streamable HTTP's JSON and SSE response forms. The
153
+ * bearer never leaves the `Authorization` header.
129
154
  */
155
+ function parseSseMessages(body) {
156
+ const messages = [];
157
+ let data = [];
158
+ const dispatch = () => {
159
+ if (data.length === 0)
160
+ return;
161
+ const payload = data.join('\n');
162
+ data = [];
163
+ if (payload === '[DONE]')
164
+ return;
165
+ try {
166
+ messages.push(JSON.parse(payload));
167
+ }
168
+ catch {
169
+ // A malformed event is not a valid MCP response. Keep looking in case a
170
+ // later event carries the request's response, then fail closed if not.
171
+ }
172
+ };
173
+ for (const rawLine of body.split('\n')) {
174
+ const line = rawLine.endsWith('\r') ? rawLine.slice(0, -1) : rawLine;
175
+ if (line === '') {
176
+ dispatch();
177
+ continue;
178
+ }
179
+ if (!line.startsWith('data:'))
180
+ continue;
181
+ const value = line.slice('data:'.length);
182
+ data.push(value.startsWith(' ') ? value.slice(1) : value);
183
+ }
184
+ dispatch();
185
+ return messages;
186
+ }
187
+ async function parseHubResponse(res, jsonRpcResponseId) {
188
+ const contentType = res.headers.get('content-type')?.toLowerCase() ?? '';
189
+ if (!contentType.includes('text/event-stream'))
190
+ return res.json();
191
+ const messages = parseSseMessages(await res.text());
192
+ if (jsonRpcResponseId !== undefined) {
193
+ return messages.find((message) => isObject(message) && message['id'] === jsonRpcResponseId) ?? {};
194
+ }
195
+ return messages.at(-1) ?? {};
196
+ }
130
197
  async function callHub(deps, req) {
131
198
  const { io, origin } = deps;
132
199
  let cred;
@@ -152,6 +219,7 @@ async function callHub(deps, req) {
152
219
  Authorization: authHeader(c),
153
220
  Accept: 'application/json',
154
221
  ...(req.body !== undefined ? { 'Content-Type': 'application/json' } : {}),
222
+ ...(req.headers ?? {}),
155
223
  };
156
224
  return hubFetch(io, resolveEndpoint(origin, req.path + (req.query ?? '')), {
157
225
  method: req.method,
@@ -174,12 +242,12 @@ async function callHub(deps, req) {
174
242
  }
175
243
  let json;
176
244
  try {
177
- json = await res.json();
245
+ json = await parseHubResponse(res, req.jsonRpcResponseId);
178
246
  }
179
247
  catch {
180
248
  json = {};
181
249
  }
182
- return { status: res.status, json };
250
+ return { status: res.status, json, mcpSessionId: res.headers.get('mcp-session-id') ?? undefined };
183
251
  }
184
252
  /** Whether an HTTP status is a 2xx success. */
185
253
  const isOk = (status) => status >= 200 && status < 300;
@@ -205,6 +273,113 @@ function toolResultFromRest(r) {
205
273
  function errorText(text) {
206
274
  return { content: [{ type: 'text', text }], isError: true };
207
275
  }
276
+ /**
277
+ * Attest the *remote* hub's ephemeral workflow contract before forwarding an
278
+ * `ephemeral:true` create. The local proxy always advertises its newest schema,
279
+ * so neither its tools/list response nor a successful inclusive REST listing
280
+ * can establish that an older selected hub honors these fields. This follows
281
+ * the Streamable HTTP lifecycle with authenticated, non-mutating requests:
282
+ * initialize, notifications/initialized, then tools/list. The negotiated
283
+ * protocol version and any returned session id ride every later request.
284
+ */
285
+ async function attestRemoteEphemeralWorkflowSupport(deps) {
286
+ const noCreate = '; no create request was sent';
287
+ const jsonRpcError = (stage, response) => {
288
+ const error = isObject(response) ? response['error'] : undefined;
289
+ if (error === undefined)
290
+ return undefined;
291
+ return `ephemeral workflow preflight remote MCP ${stage} returned JSON-RPC error ${JSON.stringify(error)}${noCreate}`;
292
+ };
293
+ const initialize = await callHub(deps, {
294
+ method: 'POST',
295
+ path: '/mcp',
296
+ headers: { Accept: 'application/json, text/event-stream' },
297
+ jsonRpcResponseId: 'owenloop-ephemeral-preflight-initialize',
298
+ body: {
299
+ jsonrpc: '2.0',
300
+ id: 'owenloop-ephemeral-preflight-initialize',
301
+ method: 'initialize',
302
+ params: {
303
+ protocolVersion: '2025-06-18',
304
+ capabilities: {},
305
+ clientInfo: { name: 'owenloop-cli-mcp', version: packageVersion() },
306
+ },
307
+ },
308
+ });
309
+ if (initialize.authFailed)
310
+ return initialize.authMessage ?? loginHint(deps.origin);
311
+ const initializeError = jsonRpcError('initialize', initialize.json);
312
+ if (initializeError !== undefined)
313
+ return initializeError;
314
+ if (!isOk(initialize.status)) {
315
+ return `ephemeral workflow preflight could not initialize remote MCP at ${deps.origin} (HTTP ${initialize.status}); no create request was sent`;
316
+ }
317
+ const initializeResult = isObject(initialize.json) ? initialize.json['result'] : undefined;
318
+ const protocolVersion = isObject(initializeResult) ? initializeResult['protocolVersion'] : undefined;
319
+ if (typeof protocolVersion !== 'string' || protocolVersion === '') {
320
+ return `ephemeral workflow preflight received no negotiated remote MCP protocol version from ${deps.origin}${noCreate}`;
321
+ }
322
+ const subsequentHeaders = {
323
+ Accept: 'application/json, text/event-stream',
324
+ 'MCP-Protocol-Version': protocolVersion,
325
+ ...(initialize.mcpSessionId === undefined ? {} : { 'Mcp-Session-Id': initialize.mcpSessionId }),
326
+ };
327
+ const initialized = await callHub(deps, {
328
+ method: 'POST',
329
+ path: '/mcp',
330
+ headers: subsequentHeaders,
331
+ body: { jsonrpc: '2.0', method: 'notifications/initialized' },
332
+ });
333
+ if (initialized.authFailed)
334
+ return initialized.authMessage ?? loginHint(deps.origin);
335
+ const initializedError = jsonRpcError('initialized notification', initialized.json);
336
+ if (initializedError !== undefined)
337
+ return initializedError;
338
+ if (!isOk(initialized.status)) {
339
+ return `ephemeral workflow preflight could not send remote MCP initialized notification to ${deps.origin} (HTTP ${initialized.status})${noCreate}`;
340
+ }
341
+ const listed = await callHub(deps, {
342
+ method: 'POST',
343
+ path: '/mcp',
344
+ headers: subsequentHeaders,
345
+ jsonRpcResponseId: 'owenloop-ephemeral-preflight-tools-list',
346
+ body: {
347
+ jsonrpc: '2.0',
348
+ id: 'owenloop-ephemeral-preflight-tools-list',
349
+ method: 'tools/list',
350
+ params: {},
351
+ },
352
+ });
353
+ if (listed.authFailed)
354
+ return listed.authMessage ?? loginHint(deps.origin);
355
+ const listedError = jsonRpcError('tools/list', listed.json);
356
+ if (listedError !== undefined)
357
+ return listedError;
358
+ if (!isOk(listed.status)) {
359
+ return `ephemeral workflow preflight could not list remote MCP tools at ${deps.origin} (HTTP ${listed.status}); no create request was sent`;
360
+ }
361
+ const response = isObject(listed.json) ? listed.json['result'] : undefined;
362
+ const tools = isObject(response) && Array.isArray(response['tools']) ? response['tools'] : undefined;
363
+ if (tools === undefined) {
364
+ return `ephemeral workflow preflight received no remote MCP tools/list result from ${deps.origin}; no create request was sent`;
365
+ }
366
+ const findTool = (name) => tools.find((tool) => isObject(tool) && tool['name'] === name);
367
+ const supportsBoolean = (tool, field) => {
368
+ const schema = tool?.['inputSchema'];
369
+ const properties = isObject(schema) ? schema['properties'] : undefined;
370
+ const property = isObject(properties) ? properties[field] : undefined;
371
+ return isObject(property) && property['type'] === 'boolean';
372
+ };
373
+ const missing = [
374
+ !supportsBoolean(findTool('create_workflow'), 'ephemeral') ? 'create_workflow.ephemeral' : undefined,
375
+ !supportsBoolean(findTool('list_workflows'), 'include_ephemeral') ? 'list_workflows.include_ephemeral' : undefined,
376
+ findTool('delete_workflow') === undefined ? 'delete_workflow' : undefined,
377
+ ].filter((item) => item !== undefined);
378
+ if (missing.length > 0) {
379
+ return `ephemeral workflow preflight found that remote MCP at ${deps.origin} lacks ${missing.join(', ')}; no create request was sent`;
380
+ }
381
+ return undefined;
382
+ }
208
383
  // ---- tool table -------------------------------------------------------------
209
384
  /** JSON-Schema fragment for a `{kind:'session'|'exec', id}` holder tag. */
210
385
  const HOLDER_SCHEMA = {
@@ -303,9 +478,11 @@ function submissionFingerprint(order, deps) {
303
478
  * judge-approve commit does not increment it. Producer claims name
304
479
  * `owes[].version`, the target the engine issued for this owed output inside
305
480
  * the claim transaction — the version the next successful commit lands, and
306
- * the version the consumer checks the proof against. See
307
- * `outputVersionForSubmission` in packages/work/src/submit-proof.ts for the
308
- * retry-safety argument; this is the same rule on the local MCP path.
481
+ * the version the consumer checks the proof against. It is re-read off the
482
+ * order on every submit and never cached, because a reject that re-arms an
483
+ * open claim re-stamps it. See `outputVersionForSubmission` in
484
+ * packages/work/src/submit-proof.ts for the retry-safety argument; this is the
485
+ * same rule on the local MCP path.
309
486
  */
310
487
  function outputVersion(order, path) {
311
488
  if (order.judge === path)
@@ -322,13 +499,13 @@ function warnMcpUnsigned(deps, reason) {
322
499
  deps.io.err(`owenloop mcp: ${reason}`);
323
500
  }
324
501
  /**
325
- * The 17 baseline tools — names, descriptions, and schemas mirror the hub's own
502
+ * The 23 baseline tools — names, descriptions, and schemas mirror the hub's own
326
503
  * HTTP-MCP toolset (owenloop-service `apps/hub-edge/src/mcp/tools.ts`); each maps
327
504
  * to an H3 `/api/*` REST mirror. Descriptions say "Scoped Identity" for the identity
328
505
  * (wire names keep `agent`), never "tool" (model-doc §0/§10).
329
506
  *
330
507
  * This is not the server's whole tool list. `runMcpCommand` assembles the full
331
- * set: these 17, plus `createAgentTool`, plus the four crew tools from
508
+ * set: these 23, plus `createAgentTool`, plus the four crew tools from
332
509
  * `buildCrewTools` (below — deliberately NOT folded in here, since they do not
333
510
  * mirror the hub's own MCP toolset), plus the conditionally-registered
334
511
  * `stageEnrollmentTool`.
@@ -337,17 +514,36 @@ function buildBaselineTools(deps) {
337
514
  return [
338
515
  {
339
516
  name: 'whats_next',
340
- description: 'THE verb. With workflow: ticks it and returns the next work order(s), or a status summary if none. Without workflow: the inbox of started instances. Serves only YOUR OWN runs by default. Pass serve_crews to partition your own runs further (intersects with each step\'s capabilities; absent or [] = no capability filter). serve_crews is ignored in inbox mode (no workflow).',
517
+ description: 'The chief-of-staff follow-up, tick, and inbox operation: relay returned work or status to the human and let crews execute it rather than treating orders as inline scratchpad work. With workflow: ticks it and returns the next work order(s), or a status summary if none. Without workflow: the inbox of started instances. Serves only YOUR OWN runs by default. Pass serve_crews to partition your own runs further (intersects with each step\'s capabilities; absent or [] = no capability filter). serve_crews is ignored in inbox mode (no workflow).',
341
518
  inputSchema: {
342
519
  type: 'object',
343
- properties: { workflow: { type: 'string' }, serve_crews: { type: 'array', items: { type: 'string' } } },
520
+ properties: {
521
+ workflow: { type: 'string' },
522
+ serve_crews: { type: 'array', items: { type: 'string' } },
523
+ serve_capabilities: {
524
+ type: 'array',
525
+ items: { type: 'string' },
526
+ description: 'Raw capability keys this caller serves (bare names and exact compounds). ' +
527
+ 'Shifts derive them from their effective rosters; other callers normally omit them.',
528
+ },
529
+ },
344
530
  additionalProperties: false,
345
531
  },
346
532
  handler: passthrough(deps, (a) => ({ method: 'POST', path: '/api/whats_next', body: a })),
347
533
  },
534
+ {
535
+ name: 'pending_gates',
536
+ description: 'Find workflow gates currently waiting on a person. A gate is an owed workflow input that no worker can supply; call this after starting or attending runs, or whenever the human asks what decisions or values need attention. Pass serve_crews to narrow the result to those crews.',
537
+ inputSchema: {
538
+ type: 'object',
539
+ properties: { serve_crews: { type: 'array', items: { type: 'string' } } },
540
+ additionalProperties: false,
541
+ },
542
+ handler: passthrough(deps, (a) => ({ method: 'POST', path: '/api/pending_gates', body: a })),
543
+ },
348
544
  {
349
545
  name: 'submit',
350
- description: 'Submit a work order output. On schema-rejected the run stays open — fix the value and submit again with the same run.',
546
+ description: 'A crew member or held-order holder returns an owed output here; a chief of staff must not use it to fabricate inline step progress. On schema rejection the run stays open — fix the value and submit again with the same run.',
351
547
  inputSchema: {
352
548
  type: 'object',
353
549
  properties: {
@@ -380,18 +576,36 @@ function buildBaselineTools(deps) {
380
576
  },
381
577
  {
382
578
  name: 'reject_artifact',
383
- description: 'Reject an upstream artifact, sending it back to its producer with a reason.',
579
+ description: 'Surface actionable feedback on a real upstream defect by sending it to its producer with a concrete reason. Rejection must be handled, never bypassed to force progress.',
384
580
  inputSchema: {
385
581
  type: 'object',
386
- properties: { workflow: { type: 'string' }, path: { type: 'string' }, reason: { type: 'string' } },
582
+ properties: {
583
+ workflow: { type: 'string' },
584
+ path: { type: 'string' },
585
+ reason: { type: 'string' },
586
+ requested: { type: 'string' },
587
+ },
387
588
  required: ['workflow', 'path', 'reason'],
388
589
  additionalProperties: false,
389
590
  },
390
591
  handler: passthrough(deps, (a) => ({ method: 'POST', path: '/api/reject_artifact', body: a })),
391
592
  },
593
+ {
594
+ name: 'retry_artifact',
595
+ description: "The deliberate human stall-clear and worker-`ask` answer path: re-arm a stalled or rejected artifact to 'owed', resetting its " +
596
+ 'reject counters, but never use it to bypass unresolved rejection feedback. `text` rides to the next producer on ' +
597
+ "the artifact's reason thread; omit it only for a bare stall-clear.",
598
+ inputSchema: {
599
+ type: 'object',
600
+ properties: { workflow: { type: 'string' }, path: { type: 'string' }, text: { type: 'string' } },
601
+ required: ['workflow', 'path'],
602
+ additionalProperties: false,
603
+ },
604
+ handler: passthrough(deps, (a) => ({ method: 'POST', path: '/api/retry_artifact', body: a })),
605
+ },
392
606
  {
393
607
  name: 'provide_input',
394
- description: 'The human-gate answer path: provide a value for a seeded/owed input.',
608
+ description: 'Relay a human answer into a seeded or owed gate by providing its input value.',
395
609
  inputSchema: {
396
610
  type: 'object',
397
611
  properties: {
@@ -406,29 +620,55 @@ function buildBaselineTools(deps) {
406
620
  },
407
621
  {
408
622
  name: 'start_run',
409
- description: 'Create a new workflow instance from a definition name, optionally seeding provided inputs.',
623
+ description: 'For a fitting multi-step playbook, start a run from its selected definition name and let its crews execute; optionally seed provided inputs. ' +
624
+ '`scope` is a free routing label recorded on the run; when omitted it defaults to this ' +
625
+ "session's repository name (the `origin` remote's last path segment) when one can be " +
626
+ 'determined, and is sent as nothing otherwise. `priority` is the rate-limit band; omit it ' +
627
+ 'and the hub applies `normal`.',
410
628
  inputSchema: {
411
629
  type: 'object',
412
- properties: { workflow_name: { type: 'string' }, provide: { type: 'object', additionalProperties: true } },
630
+ properties: {
631
+ workflow_name: { type: 'string' },
632
+ provide: { type: 'object', additionalProperties: true },
633
+ scope: { type: 'string' },
634
+ // Unlike crew `kind`/`principalKind`, this is a fixed local wire
635
+ // contract, so the MCP schema rejects an out-of-set value too.
636
+ priority: { type: 'string', enum: ['low', 'normal', 'high'] },
637
+ },
413
638
  required: ['workflow_name'],
414
639
  additionalProperties: false,
415
640
  },
416
- handler: passthrough(deps, (a) => ({ method: 'POST', path: '/api/start_run', body: a })),
641
+ handler: passthrough(deps, (a) => ({
642
+ method: 'POST',
643
+ path: '/api/start_run',
644
+ // A default, never an override: explicit `scope`, including '', wins.
645
+ body: deps.repoScope !== undefined && !('scope' in a) ? { ...a, scope: deps.repoScope } : a,
646
+ })),
417
647
  },
418
648
  {
419
649
  name: 'create_workflow',
420
- description: 'The authoring hard gate: parse + load a workflow def YAML through the engine. Only stored if it loads clean. On failure returns the engine/parser error verbatim. Idempotent: re-pushing identical content is a no-op success (unchanged: true with the existing version); changed content version-forwards.',
650
+ description: 'Only when no catalog entry fits and the human chooses ordinary authoring, use this parse-and-load hard gate for a workflow definition YAML. It is stored only if it loads clean; failures return the engine/parser error verbatim. Idempotent: re-pushing identical content is a no-op success (unchanged: true with the existing version); changed content version-forwards.',
421
651
  inputSchema: {
422
652
  type: 'object',
423
- properties: { yaml: { type: 'string' } },
653
+ properties: { yaml: { type: 'string' }, bundle_digest: { type: 'string' }, ephemeral: { type: 'boolean' } },
424
654
  required: ['yaml'],
425
655
  additionalProperties: false,
426
656
  },
427
- handler: passthrough(deps, (a) => ({ method: 'POST', path: '/api/create_workflow', body: a })),
657
+ handler: async (a) => {
658
+ if (a['ephemeral'] === true) {
659
+ const preflightFailure = await attestRemoteEphemeralWorkflowSupport(deps);
660
+ if (preflightFailure !== undefined)
661
+ return errorText(preflightFailure);
662
+ }
663
+ const r = await callHub(deps, { method: 'POST', path: '/api/create_workflow', body: a });
664
+ if (r.authFailed)
665
+ return errorText(r.authMessage ?? loginHint(deps.origin));
666
+ return toolResultFromRest(r);
667
+ },
428
668
  },
429
669
  {
430
670
  name: 'get_workflow',
431
- description: 'Def summary and full workflow bundle: steps with consumes/produces, schemas, judges, each step\'s prompt body, model/executor/command, and x extension bags, plus mermaid source and the def content hash/version.',
671
+ description: 'Inspect a promising catalog entry in full before selecting it: def summary and bundle with steps, consumes/produces, schemas, judges, each step\'s prompt body, model/executor/command, and x extension bags, plus mermaid source and the def content hash/version.',
432
672
  inputSchema: {
433
673
  type: 'object',
434
674
  properties: { name: { type: 'string' } },
@@ -442,13 +682,44 @@ function buildBaselineTools(deps) {
442
682
  },
443
683
  {
444
684
  name: 'list_workflows',
445
- description: 'Names, titles, step counts, and def content hash/version of every loaded workflow definition.',
446
- inputSchema: { type: 'object', properties: {}, additionalProperties: false },
447
- handler: passthrough(deps, () => ({ method: 'GET', path: '/api/workflows' })),
685
+ description: 'Discover published workflow definitions and decide which one fits a task.',
686
+ inputSchema: { type: 'object', properties: { include_ephemeral: { type: 'boolean' } }, additionalProperties: false },
687
+ handler: passthrough(deps, (a) => ({
688
+ method: 'GET',
689
+ path: '/api/workflows',
690
+ ...('include_ephemeral' in a ? { query: `?include_ephemeral=${String(a['include_ephemeral'])}` } : {}),
691
+ })),
692
+ },
693
+ {
694
+ name: 'search_workflows',
695
+ description: 'Search the same published catalog as a context-smaller ranked read when it is too large to read whole or the host cannot spend the full-list context. For smaller catalogs (roughly below 75 definitions), reading the full listing can support better selection.',
696
+ // Deliberately stricter than the REST route, which ignores unknown fields: MCP callers fail locally without a hub round-trip.
697
+ inputSchema: {
698
+ type: 'object',
699
+ properties: {
700
+ query: { type: 'string' },
701
+ limit: { type: 'integer', minimum: 1 },
702
+ include_ephemeral: { type: 'boolean' },
703
+ },
704
+ required: ['query'],
705
+ additionalProperties: false,
706
+ },
707
+ handler: passthrough(deps, (a) => ({ method: 'POST', path: '/api/search_workflows', body: a })),
708
+ },
709
+ {
710
+ name: 'delete_workflow',
711
+ description: 'Retire an ephemeral workflow live name. Refuses while an active root references its exact pinned definition closure.',
712
+ inputSchema: {
713
+ type: 'object',
714
+ properties: { name: { type: 'string', minLength: 1 } },
715
+ required: ['name'],
716
+ additionalProperties: false,
717
+ },
718
+ handler: passthrough(deps, (a) => ({ method: 'POST', path: '/api/delete_workflow', body: a })),
448
719
  },
449
720
  {
450
721
  name: 'get_status',
451
- description: 'engine.status verbatim plus a plain-English one-paragraph rendering.',
722
+ description: 'Inspect and relay a run\'s current state rather than performing its work: engine.status verbatim plus a plain-English one-paragraph rendering.',
452
723
  inputSchema: {
453
724
  type: 'object',
454
725
  properties: { workflow: { type: 'string' } },
@@ -462,7 +733,7 @@ function buildBaselineTools(deps) {
462
733
  },
463
734
  {
464
735
  name: 'heartbeat',
465
- description: 'Touch the liveness timestamp on an open run so it is not reaped mid-step (the design-doc "renew"). The first heartbeat on a freshly served claim is "first contact" — it closes the ~2-minute pickup window. Optionally tag who holds the claim (session or exec).',
736
+ description: 'A held-run liveness and first-contact signal, distinct from Shift presence: touch an open run so it is not reaped mid-step (the design-doc "renew"). The first heartbeat on a freshly served claim closes the ~2-minute pickup window. Optionally tag who holds the claim (session or exec).',
466
737
  inputSchema: {
467
738
  type: 'object',
468
739
  properties: { workflow: { type: 'string' }, run: { type: 'string' }, holder: HOLDER_SCHEMA },
@@ -473,7 +744,7 @@ function buildBaselineTools(deps) {
473
744
  },
474
745
  {
475
746
  name: 'get_order',
476
- description: 'Re-fetch the persisted order packet for a run you hold, plus its live lease state (claimed/claimedAt/heartbeatAt/outcome) — for a holder rebinding to work it already had served. Optionally tag who holds the claim.',
747
+ description: 'For a holder rebinding to a persisted order already served to it, re-fetch that packet and its live lease state (claimed/claimedAt/heartbeatAt/outcome); this is not workflow discovery. Optionally tag who holds the claim.',
477
748
  inputSchema: {
478
749
  type: 'object',
479
750
  properties: { workflow: { type: 'string' }, run: { type: 'string' }, holder: HOLDER_SCHEMA },
@@ -484,7 +755,7 @@ function buildBaselineTools(deps) {
484
755
  },
485
756
  {
486
757
  name: 'release',
487
- description: 'Voluntarily give back a claim so its order is re-offered without waiting out the reap TTL. Either target one run (`workflow`+`run`) or drain a session (`session`). Idempotent: releasing an unheld/closed run is a no-op, never an error.',
758
+ description: 'Give a held claim back so its order can be re-offered without waiting for the reap TTL. Either target one run (`workflow`+`run`) or drain a session (`session`). Idempotent: releasing an unheld/closed run is a no-op, never an error.',
488
759
  inputSchema: {
489
760
  type: 'object',
490
761
  properties: { workflow: { type: 'string' }, run: { type: 'string' }, session: { type: 'string' } },
@@ -505,7 +776,7 @@ function buildBaselineTools(deps) {
505
776
  },
506
777
  {
507
778
  name: 'publish_event',
508
- description: 'Publish an event against a contract: validate the payload against the pinned contract version schema, then start one run per matched active subscription (best-effort, per-target isolation). Returns the per-match outcome. Requires agent scope `run`.',
779
+ description: 'Delegate event-driven work through matching subscriptions: validate the payload against the pinned contract version schema, then start one run per matched active subscription (best-effort, per-target isolation). Returns the per-match outcome. Requires agent scope `run`.',
509
780
  inputSchema: {
510
781
  type: 'object',
511
782
  properties: {
@@ -520,18 +791,24 @@ function buildBaselineTools(deps) {
520
791
  },
521
792
  {
522
793
  name: 'list_subscriptions',
523
- description: "The org's contract subscriptions — what a publish will cascade into. Creating/revoking a subscription is admin-only and deliberately not exposed here.",
794
+ description: "Preview which playbooks a publish may start through the org's contract subscriptions. Creating or revoking a subscription is admin-only and deliberately not exposed here.",
524
795
  inputSchema: { type: 'object', properties: {}, additionalProperties: false },
525
796
  handler: passthrough(deps, () => ({ method: 'GET', path: '/api/subscriptions' })),
526
797
  },
527
798
  {
528
799
  name: 'presence_ping',
529
- description: 'Register or refresh this Shift in the presence registry: its name, the crews it serves, and optionally which process incarnation is reporting. Call it on a ~60s cadence; the entry reads as offline once ~3 min have passed since its last ping — derived when the registry is read, nothing sweeps it. Observability only: it never affects serving and never wakes anyone. This is NOT the lease heartbeat — that is the separate `heartbeat` tool, one per claimed run, whose lapse gets the claim reaped. Every field is overwrite, NOT keep-previous: omitting serve_crews stores an empty set, which means "every crew this principal belongs to" (the same reading whats_next gives an empty serve_crews) and NOT "no crews"; omitting shift_id/started_at clears them.',
800
+ description: 'Report Shift availability only by registering or refreshing its presence: name, crews served, and optionally process incarnation. Call it on a ~60s cadence; the entry reads as offline once ~3 min have passed since its last ping — derived when the registry is read, nothing sweeps it. Observability only: it never affects serving and never wakes anyone. This is NOT the lease `heartbeat`, which is per claimed run and whose lapse reaps that claim. Every field overwrites, not keeps-previous: omitting serve_crews stores an empty set, meaning every crew this principal belongs to (the same reading whats_next gives an empty serve_crews), not no crews; omitting shift_id/started_at clears them.',
530
801
  inputSchema: {
531
802
  type: 'object',
532
803
  properties: {
533
804
  name: { type: 'string' },
534
805
  serve_crews: { type: 'array', items: { type: 'string' } },
806
+ serve_capabilities: {
807
+ type: 'array',
808
+ items: { type: 'string' },
809
+ description: 'Raw capability keys this caller serves (bare names and exact compounds). ' +
810
+ 'Shifts derive them from their effective rosters; other callers normally omit them.',
811
+ },
535
812
  shift_id: { type: 'string' },
536
813
  started_at: { type: 'number' },
537
814
  },
@@ -542,13 +819,25 @@ function buildBaselineTools(deps) {
542
819
  },
543
820
  {
544
821
  name: 'list_shifts',
545
- description: "Your principal's registered Shifts, each with an online/offline flag (derived at read time from its last ping, ~3 min), how long since it was last seen, the crews it serves (returned as `crews`; an empty list means every crew this principal belongs to, not none), and the reporting process incarnation (`shiftId`/`startedAt`) when the hub recorded one.",
822
+ description: "Show available or offline execution coverage for this principal so gaps can be relayed: registered Shifts with an online/offline flag (derived at read time from its last ping, ~3 min), last-seen age, crews served (returned as `crews`; an empty list means every crew this principal belongs to, not none), and recorded process incarnation (`shiftId`/`startedAt`).",
546
823
  inputSchema: { type: 'object', properties: {}, additionalProperties: false },
547
824
  handler: passthrough(deps, () => ({ method: 'GET', path: '/api/shifts' })),
548
825
  },
826
+ {
827
+ name: 'get_rosters',
828
+ description: "Inspect post-crew routing choices rather than execute work: the org's roster cascade has one org-global capability table plus optional per-crew tables, whose rows select harness/model/effort after the hub has already routed work to a crew.",
829
+ inputSchema: { type: 'object', properties: {}, additionalProperties: false },
830
+ handler: passthrough(deps, () => ({ method: 'GET', path: '/api/rosters' })),
831
+ },
832
+ {
833
+ name: 'list_harness_models',
834
+ description: "Read-only roster-planning data: the hub's known harnesses and model snapshots, including each model's supported effort values. Roster writes stay in the terminal CLI.",
835
+ inputSchema: { type: 'object', properties: {}, additionalProperties: false },
836
+ handler: passthrough(deps, () => ({ method: 'GET', path: '/api/harness_models' })),
837
+ },
549
838
  {
550
839
  name: 'wake',
551
- description: 'A cheap "has anything relevant to you changed since cursor X" pre-check for a polling loop — returns { cursor, changed }. Keep the returned cursor and pass it next time; call whats_next ONLY when changed is true. Omit cursor to bootstrap. NOT a substitute for whats_next — it never returns work orders, only whether to ask.',
840
+ description: 'The cheap place to park between changes: a polling pre-check returning only { cursor, changed }. Keep the returned cursor and pass it next time; call whats_next ONLY when changed is true. Omit cursor to bootstrap. It is not a substitute for whats_next — it never returns work orders, only whether to ask.',
552
841
  inputSchema: {
553
842
  type: 'object',
554
843
  properties: { cursor: { type: 'integer', minimum: 0 } },
@@ -575,7 +864,7 @@ const AGENT_NAME_RE = /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/;
575
864
  function createAgentTool(deps) {
576
865
  return {
577
866
  name: 'create_agent',
578
- description: 'Create a NEW Scoped Identity on the hub and store its credential locally. NEVER returns the token — it is written to this machine\'s credential store only. Refuses a name that is already taken. Mints with `work` scope by default; pass `scopes` (e.g. ["work","run"]) to choose.',
867
+ description: 'Administrative setup that enables crews to execute runs, not the normal task path: create a NEW Scoped Identity on the hub and store its credential locally. NEVER returns the token — it is written to this machine\'s credential store only. Refuses a name that is already taken. Mints with `work` scope by default; pass `scopes` (e.g. ["work","run"]) to choose.',
579
868
  inputSchema: {
580
869
  type: 'object',
581
870
  properties: {
@@ -636,11 +925,11 @@ function createAgentTool(deps) {
636
925
  },
637
926
  };
638
927
  }
639
- /** Tool 19 (gated) — `stage_enrollment`: a plain passthrough (join codes are transcript-legal per model-doc §6). */
928
+ /** Tool 20 (gated) — `stage_enrollment`: a plain passthrough (join codes are transcript-legal per model-doc §6). */
640
929
  function stageEnrollmentTool(deps) {
641
930
  return {
642
931
  name: 'stage_enrollment',
643
- description: 'Stage a Scoped Identity enrollment on the hub, returning a join code the enrolling machine redeems. A join code is transferred authority, not a credential — it is safe to surface.',
932
+ description: 'Administrative setup that enables crews to execute runs, not the normal task path: stage a Scoped Identity enrollment on the hub, returning a join code the enrolling machine redeems. A join code is transferred authority, not a credential — it is safe to surface.',
644
933
  inputSchema: {
645
934
  type: 'object',
646
935
  properties: {
@@ -687,7 +976,7 @@ function buildCrewTools(deps) {
687
976
  return [
688
977
  {
689
978
  name: 'list_crews',
690
- description: "The org's crews, each with its membership rows inline (principalKind/principalId/addedBy/addedAt) — " +
979
+ description: "Inspect execution capacity and membership before a run or membership change: the org's crews, each with its membership rows inline (principalKind/principalId/addedBy/addedAt) — " +
691
980
  'one call, no per-crew fan-out. An org with no crews at all is a normal empty result, not an error. ' +
692
981
  "The org's reserved ORPHAN crew (kind: \"orphan\", or a name starting \"orphan:\") IS returned when it " +
693
982
  'exists and is deliberately NOT filtered out — it is where the hub re-homes work whose crew was ' +
@@ -699,7 +988,7 @@ function buildCrewTools(deps) {
699
988
  },
700
989
  {
701
990
  name: 'create_crew',
702
- description: "Create a crew on the hub org. `kind` is 'personal' or 'shared', forwarded verbatim — the hub is the " +
991
+ description: "Configure who can execute by creating a crew on the hub org. `kind` is 'personal' or 'shared', forwarded verbatim — the hub is the " +
703
992
  "enforcement of record for legal values ('orphan' is reserved for the hub's own crew and is refused). " +
704
993
  "`ownerMemberId` is required for a 'personal' crew and is simply omitted from the request when not " +
705
994
  'passed. NOT admin-only: an org admin may create any crew, AND a non-admin may create a personal crew ' +
@@ -721,7 +1010,7 @@ function buildCrewTools(deps) {
721
1010
  },
722
1011
  {
723
1012
  name: 'add_crew_member',
724
- description: "Add one principal to a crew. `principalKind` is 'member' (a human) or 'agent' (a Scoped Identity), " +
1013
+ description: "Configure who can execute by adding one principal to a crew. `principalKind` is 'member' (a human) or 'agent' (a Scoped Identity), " +
725
1014
  'forwarded verbatim; the hub validates it. NOT admin-only: an org admin may act on any crew, AND the ' +
726
1015
  'OWNER of a personal crew may add members to that crew without being an admin. HTTP 400 (not a ' +
727
1016
  'permissions error, and NOT tolerant): an unknown crewId, an unknown principalId, or a principal that ' +
@@ -743,7 +1032,7 @@ function buildCrewTools(deps) {
743
1032
  },
744
1033
  {
745
1034
  name: 'remove_crew_member',
746
- description: 'Remove one principal from a crew. TOLERANT: removing a principal that was never a member is a normal ' +
1035
+ description: 'Configure who can execute by removing one principal from a crew. TOLERANT: removing a principal that was never a member is a normal ' +
747
1036
  'success — HTTP 200 with removed:false, NOT a 404. Read the `removed` boolean rather than treating a ' +
748
1037
  'false as a failure. An unknown crewId is DIFFERENT and is an HTTP 400 error. NOT admin-only: same ' +
749
1038
  'self-service carve-out as add_crew_member — an org admin, or the owner of the personal crew being ' +
@@ -814,7 +1103,7 @@ async function shouldRegisterEnrollment(deps) {
814
1103
  */
815
1104
  export async function runMcpCommand(io, opts) {
816
1105
  const origin = resolveMcpOrigin(io, opts.hubFlag);
817
- const deps = { io, origin };
1106
+ const deps = { io, origin, repoScope: resolveRepoScope(io) };
818
1107
  const tools = [...buildBaselineTools(deps), createAgentTool(deps), ...buildCrewTools(deps)];
819
1108
  if (await shouldRegisterEnrollment(deps))
820
1109
  tools.push(stageEnrollmentTool(deps));
@@ -22,22 +22,25 @@
22
22
  * `pumpStdin` wires the real `process.stdin`/`process.stdout` in the roles.
23
23
  *
24
24
  * Supported methods (the subset an MCP host needs):
25
- * - `initialize` → capabilities `{tools:{}}`, serverInfo, and the
26
- * agreed protocolVersion (echo the client's when
27
- * recognized, else answer with ours).
25
+ * - `initialize` → capabilities `{tools:{}}`, serverInfo,
26
+ * instructions, and the agreed protocolVersion
27
+ * (echo the client's when recognized, else
28
+ * answer with ours).
28
29
  * - `notifications/initialized` → no-op (no response; it is a notification).
29
30
  * - `ping` → `{}`.
30
31
  * - `tools/list` → the registered tool defs.
31
- * - `tools/call` → dispatch to the tool handler; the result is
32
- * `{content:[{type:'text',text:<JSON>}], isError?}`.
32
+ * - `tools/call` → validate arguments against the registered
33
+ * input schema, then dispatch to the handler;
34
+ * the result is `{content:[{type:'text',text:<JSON>}], isError?}`.
33
35
  * - `notifications/cancelled` → abort a tracked in-flight `tools/call`; the
34
36
  * aborted call sends NO response frame.
35
37
  * - outbound `notifications/progress` when a call carried
36
38
  * `params._meta.progressToken` (via `ctx.sendProgress`).
37
39
  *
38
40
  * Errors: unknown method → -32601; malformed JSON / bad envelope → -32700;
39
- * invalid params → -32602. A notification (no `id`) never gets a response, even
40
- * on error. The process must never crash on a bad line.
41
+ * invalid params (including a tool-schema mismatch) → -32602. A notification
42
+ * (no `id`) never gets a response, even on error. The process must never crash
43
+ * on a bad line.
41
44
  */
42
45
  export declare const PARSE_ERROR = -32700;
43
46
  export declare const INVALID_REQUEST = -32600;