@awebai/oats 0.49.0 → 0.50.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.
package/bin/oats.mjs CHANGED
@@ -30,7 +30,7 @@ import {
30
30
  LAYERS, OATS_VERSION, manifestOperations, upgradeHomeMeta,
31
31
  capabilityManifests, capabilityTrust, capabilityExecutablePath,
32
32
  officialPackageCatalog, officialCatalogFile, officialCapabilityAliases, resolvedFromHome, resolvedFromPrepared, teamEnv, isWorkspaceHome, preWorkspaceHome, isCapturedHome, capturedHomeRefusal, composeInstanceAgentsMd, parseYamlNested, withConfigFile,
33
- findInstanceHome, findInstanceHomes, enclosingInstanceHome, logicalCwd, readableInstanceHomes, workspaceOf, ensureRoot, findRoot, findAgent, findAgentAt, legacyLocalAgents, legacyCapturedHomes, listAgents, listInstances, servedIdentityLine, spawnInstanceAsync, instanceSoulDir, stableSoulId, preparedSoulIdOf, recordedKernelBin, launchConfigsAt, launchPromptPolicyAt, LAUNCH_PROMPT_UPDATE_WARNING, launchReportFor, explicitInstanceName, retireInstance, RETIRE_SELECTED_HOME, inspectInstanceSession, inputInstanceSession, attachInstanceSession, startInstanceSession, defaultRepo, RELATIONS, validateLaunchConfig, validateLaunchConfigDefaults, renderLaunchRecipe, describeLaunchCommand, redactLaunchRecipe, withSafeTaskPrompt, LAUNCH_HARNESSES, planLaunch, redactLaunchCommand, restartInstanceSession,
33
+ findInstanceHome, findInstanceHomes, processScanInformation, enclosingInstanceHome, logicalCwd, readableInstanceHomes, workspaceOf, ensureRoot, findRoot, findAgent, findAgentAt, legacyLocalAgents, legacyCapturedHomes, listAgents, listInstances, servedIdentityLine, spawnInstanceAsync, instanceSoulDir, stableSoulId, preparedSoulIdOf, recordedKernelBin, launchConfigsAt, launchPromptPolicyAt, LAUNCH_PROMPT_UPDATE_WARNING, launchReportFor, explicitInstanceName, retireInstance, RETIRE_SELECTED_HOME, inspectInstanceSession, inputInstanceSession, attachInstanceSession, startInstanceSession, defaultRepo, RELATIONS, validateLaunchConfig, validateLaunchConfigDefaults, renderLaunchRecipe, describeLaunchCommand, redactLaunchRecipe, withSafeTaskPrompt, LAUNCH_HARNESSES, planLaunch, redactLaunchCommand, restartInstanceSession,
34
34
  FAILED_SPAWN_BRANCH_LEFT, RETIRE_DELETE_BRANCH_REFUSED,
35
35
  } from "../lib/core.mjs";
36
36
  import {
@@ -55,13 +55,14 @@ import { receiveAttachment, uploadAttachment, readStreamBounded, MAX_ATTACHMENT_
55
55
  import { observeInstanceGit, diffInstanceFile } from "../lib/instance-git.mjs";
56
56
  import { planStop, applyStop, planRetire, descendantsOf, resolveInstance as resolveInstanceForCli } from "../lib/instance-lifecycle.mjs";
57
57
  import { extraWorktreeLines, formatBytes, workRecoveryLines } from "../lib/retire-output.mjs";
58
+ import { retainedRecoveryLines, retainedWorktreeLines, retainedWorktrees } from "../lib/retained-after-retire.mjs";
58
59
  const await_import_lifecycle = () => ({ resolveInstance: resolveInstanceForCli });
59
60
  import { homeTarget, soulTarget, isWorkspaceContext, inspectDocument, withComposedInstructions, readinessDocument, policyOf, policySoul, manifestMissingRequires, INSPECT_OPERATIONS_API } from "../lib/instance-inspect.mjs";
60
61
  import { readEvents, setWaiting, incarnationOf } from "../lib/instance-events.mjs";
61
62
 
62
63
  const rawArgs = process.argv.slice(2);
63
64
  /** The kernel's switches: a value never rides one (`--yolo=false` must not turn yolo on). */
64
- const KERNEL_SWITCHES = new Set(["allow-child-spawns", "apply", "check", "clear", "delete-branch", "discard-worktree", "dry-run", "ephemeral", "force", "help", "host", "if-absent", "install-oats", "instructions", "json", "keep-dir", "keep-env", "no-child-spawns", "no-default", "no-launch", "no-recursive", "no-yolo", "plan", "policy", "preview", "print", "replace", "self", "verbose", "yes", "yolo"]);
65
+ const KERNEL_SWITCHES = new Set(["allow-child-spawns", "apply", "check", "clear", "delete-branch", "discard-worktree", "dry-run", "ephemeral", "force", "help", "host", "if-absent", "install-oats", "instructions", "json", "keep-dir", "keep-env", "no-child-spawns", "no-default", "no-launch", "no-recursive", "no-yolo", "plan", "policy", "preview", "print", "replace", "run-source", "self", "verbose", "yes", "yolo"]);
65
66
  /** `--flag=value` is `--flag value`: every kernel reader (flag(), valueFlag(), the onboard and
66
67
  * routed-command loops) then applies the spaced form's validation to it. `problem` is an empty
67
68
  * `--flag=`, a switch given a value, or a value that is itself an option (`--model=--yolo`):
@@ -97,7 +98,7 @@ const OWN_ARGV_COMMANDS = new Set(["capture", "recall", "setup", "experimental"]
97
98
  * probe) and in `status --json`, which a remote roster relays as the host's (feature
98
99
  * server-probe-features, lib/servers.mjs hostFeatures). ONE list for both, emitted at output
99
100
  * time, never stored. A name must pass hostFeatures's check (test/cli-json-contract.test.mjs). */
100
- const KERNEL_FEATURES = ["retire-home", "session-start", "session-restart", "launch-config", "schedule", "schedule-host-caps", "session-upload", "operations", "instance-git", "instance-git-remote", "souls-declarations", "lifecycle-plans", "retire-retention", "readiness", "spawn-preview", "instance-events", "instance-events-2", "schedule-history", "schedule-read-2", "spawn-preview-2", "spawn-idempotency", "spawn-idempotency-2", "spawn-apply-2", "workspace-v2", "instance-modules", "spawn-provider-payload", "served-identity", "packages-no-approval", "spawn-name", "settings-origins", "team-model-3", "settings-declared", "capabilities-private", "layers-from", "harness", "package-souls", "triggers", "automations", "desktop-facts", "launch-preference", "preview-composed-from", "observe-max-age", "spawn-preview-max-age", "launch-config-default", "capability-show", "capture-file", "workspace-identity", "server-connect", "capability-route", "servers-per-workspace", "operator-default-soul", "waiting-on-you", "automation-descriptions", "souls-capabilities", "soul-composed-instructions", "teams-conditional-default", "server-probe-features", "worktree-event"];
101
+ const KERNEL_FEATURES = ["retire-home", "session-start", "session-restart", "launch-config", "schedule", "schedule-host-caps", "session-upload", "operations", "instance-git", "instance-git-remote", "souls-declarations", "lifecycle-plans", "retire-retention", "readiness", "spawn-preview", "instance-events", "instance-events-2", "schedule-history", "schedule-read-2", "spawn-preview-2", "spawn-idempotency", "spawn-idempotency-2", "spawn-apply-2", "workspace-v2", "instance-modules", "spawn-provider-payload", "served-identity", "packages-no-approval", "spawn-name", "settings-origins", "team-model-3", "settings-declared", "capabilities-private", "layers-from", "harness", "package-souls", "triggers", "automations", "desktop-facts", "launch-preference", "preview-composed-from", "observe-max-age", "spawn-preview-max-age", "launch-config-default", "capability-show", "capture-file", "workspace-identity", "server-connect", "capability-route", "servers-per-workspace", "operator-default-soul", "waiting-on-you", "automation-descriptions", "souls-capabilities", "soul-composed-instructions", "teams-conditional-default", "server-probe-features", "worktree-event", "trigger-sources"];
101
102
  /** Commands `--server <id>` runs on a registered server. */
102
103
  const ROUTED_COMMANDS = new Set(["spawn", "retire", "status", "session", "okf", "schedule", "inspect", "operation", "launch-config", "readiness", "instance"]);
103
104
  const flag = (name) => {
@@ -726,6 +727,14 @@ async function doctorJson(dir) {
726
727
  function legacyLayoutProblems(root) {
727
728
  return [legacyLocalAgents(root), legacyCapturedHomes(root)].filter(Boolean);
728
729
  }
730
+ /** What retires left in the deployment (#703 part 2a), read-only: the
731
+ * `retained-recovery:` and `retained-worktree:` information lines, as one
732
+ * block per kind (a count line, then one line per item). */
733
+ function doctorRetained(ws) {
734
+ const deployment = dirname(ws.local.path);
735
+ const kept = retainedWorktrees(deployment);
736
+ return [retainedRecoveryLines(join(deployment, "agents"), kept), retainedWorktreeLines(kept)].filter((block) => block.length);
737
+ }
729
738
  async function doctorWorkspaceJson(ctx, soulName, ws) {
730
739
  const composition = await doctorComposition(ctx, soulName, ws, (code, msg, details) => jsonFail(code, msg, details));
731
740
  const agentsRoot = join(dirname(ws.local.path), "agents");
@@ -739,7 +748,7 @@ async function doctorWorkspaceJson(ctx, soulName, ws) {
739
748
  schemaVersion: 1, workspaceApi: 2, context: ctx,
740
749
  workspace: { file: ws.local.path, ref: ws.local.workspace },
741
750
  workspaceError: ws.localError, lockFile: ws.lockFile, packages: ws.packages, lockError: ws.lockError,
742
- information: [...(operationalKnowledgeNote(composition, soulName) ? [operationalKnowledgeNote(composition, soulName)] : []), ...localTeams.information, ...schedules.information, ...operator.information, ...hookEvents.information],
751
+ information: [...(operationalKnowledgeNote(composition, soulName) ? [operationalKnowledgeNote(composition, soulName)] : []), ...localTeams.information, ...schedules.information, ...operator.information, ...hookEvents.information, ...processScanInformation(), ...doctorRetained(ws).flat()],
743
752
  composedInstructions: composition?.text, instructionBlocks: composition?.blocks,
744
753
  ...(problems.length ? { problems } : {}),
745
754
  warnings: hookEvents.warnings,
@@ -784,7 +793,8 @@ async function doctor(dir) {
784
793
  for (const p of operator.problems) console.log(`\n! ${p.code}: ${p.message}\n ${p.remedy}`);
785
794
  const hookEvents = composition ? { warnings: composition.warnings, information: [] } : await doctorHookWarnings(ws);
786
795
  for (const w of hookEvents.warnings) console.log(`\nwarning ${w.code} ${w.message}`);
787
- for (const line of [...localTeams.information, ...schedules.information, ...operator.information, ...hookEvents.information]) console.log(`\nINFO: ${line}`);
796
+ for (const line of [...localTeams.information, ...schedules.information, ...operator.information, ...hookEvents.information, ...processScanInformation()]) console.log(`\nINFO: ${line}`);
797
+ for (const block of doctorRetained(ws)) console.log(`\n${block.map((line) => `INFO: ${line}`).join("\n")}`);
788
798
  if (soulName) {
789
799
  const information = operationalKnowledgeNote(composition, soulName);
790
800
  if (information) console.log(`\nINFO: ${information}`);
@@ -1364,7 +1374,7 @@ function sayReadNotices() {
1364
1374
  }
1365
1375
  /** Which kernel command forms take --max-age: THE allow-list (docs/desktop-cli-api.md "Observation reuse").
1366
1376
  * → null when this form reads with observation reuse, else the E_BAD_ARGS message. `head` is argv before `--`. */
1367
- const MAX_AGE_READS = "status, workspace status, souls, capabilities, capabilities show, inspect --soul|--home, spawn --preview, and the read forms of teams and soul teams";
1377
+ const MAX_AGE_READS = "status, workspace status, souls, capabilities, capabilities show, inspect --soul|--home, spawn --preview, trigger poll, and the read forms of teams and soul teams";
1368
1378
  function maxAgeRefusal(command, head) {
1369
1379
  const word = (i) => (head[i] !== undefined && !head[i].startsWith("--") ? head[i] : undefined);
1370
1380
  const refuse = (form) => `--max-age is not accepted by \`oats ${form}\`: only the read verbs reuse observations (${MAX_AGE_READS})`;
@@ -1377,6 +1387,8 @@ function maxAgeRefusal(command, head) {
1377
1387
  case "teams": return word(1) === undefined ? null : refuse(`teams ${word(1)}`);
1378
1388
  // `soul teams` only reads (its edit flags were removed in 0.38.0, and refuse as such).
1379
1389
  case "soul": return word(1) === "teams" ? null : refuse(["soul", word(1)].filter(Boolean).join(" "));
1390
+ // A capability source's poll resolves its soul as a read (the tick's child passes --max-age 600).
1391
+ case "trigger": return word(1) === "poll" ? null : refuse(["trigger", word(1)].filter(Boolean).join(" "));
1380
1392
  default: {
1381
1393
  const sub = ["package", "schedule", "session", "trigger", "automations", "launch-config", "server", "instance", "operation", "pane"].includes(command) ? word(1) : undefined;
1382
1394
  return refuse([command, sub].filter(Boolean).join(" "));
@@ -1718,7 +1730,9 @@ async function addWorkspaceAutomation(desc, { id, body, description }) {
1718
1730
  const content = A.automationFileText(desc, { id, description: description || undefined, runsOn, owner, body });
1719
1731
  const parsed = A.parseAutomationFile(desc, { stem: id, path: `${desc.folder}/${id}.yaml`, bytes: Buffer.from(content), member: name, repoKey: row.key, commit: row.commit });
1720
1732
  if (parsed.problem) bail(parsed.problem.code, parsed.problem.message, { path: parsed.problem.path });
1721
- await desc.expand(parsed.entry);
1733
+ const def = await desc.expand(parsed.entry);
1734
+ // A capability source's trigger means something only against its soul's resolution: checked before the file is written.
1735
+ if (desc.kind === "trigger") await (await import("../lib/triggers.mjs")).checkAddMeaning(ctx.deploymentDir, def, { remoteOptions: ctx.remoteOptions });
1722
1736
  const sameRepo = (url) => { try { return remoteModule.parseRepoRef(url).key === row.key; } catch { return false; } };
1723
1737
  const at = A.memberCheckoutFor(dirFlag(), desc, id, { sameRepo });
1724
1738
  const file = { member: name, repoKey: row.key, path: `${desc.folder}/${id}.yaml`, content };
@@ -2155,6 +2169,17 @@ async function capabilityShowCmd(bail) {
2155
2169
  if (skill.filesTruncated) console.log(` … more files (the first ${S.FILES_PER_SKILL} are listed)`);
2156
2170
  }
2157
2171
  }
2172
+ if (doc.triggerSources !== undefined) {
2173
+ // As declared (a malformed declaration is shown, never refused): names, commands and events, made safe to print.
2174
+ const { safeText } = await import("../lib/refused-text.mjs");
2175
+ const decl = doc.triggerSources && typeof doc.triggerSources === "object" && !Array.isArray(doc.triggerSources) ? doc.triggerSources : null;
2176
+ console.log(decl && Object.keys(decl).length ? " trigger sources:" : ` trigger sources: ${decl ? "(none)" : "(malformed — see trigger source problems)"}`);
2177
+ for (const [n, src] of Object.entries(decl ?? {})) {
2178
+ const o = src && typeof src === "object" ? src : {};
2179
+ console.log(` ${safeText(n, 60)} command ${typeof o.command === "string" ? safeText(o.command, 60) : "?"} events ${Array.isArray(o.events) ? o.events.map((e) => safeText(String(e), 40)).join(",") : "?"}${typeof o.description === "string" ? ` — ${safeText(o.description, 200)}` : ""}`);
2180
+ }
2181
+ for (const p of doc.triggerSourceProblems ?? []) console.log(` trigger source problem: ${p.pointer} — ${safeText(p.message, 300)}`);
2182
+ }
2158
2183
  for (const p of doc.problems) console.log(` problem: ${p.code}${p.path ? ` ${p.path}` : ""} — ${p.message}`);
2159
2184
  for (const w of doc.warnings) console.log(` warning ${w.code} ${w.message}`);
2160
2185
  console.log(`\n a file's text: oats capabilities show ${doc.name}${doc.kind === "package" ? ` --package ${doc.package}` : ""} --file <path>`);
@@ -2623,8 +2648,13 @@ async function spawnCmd() {
2623
2648
  if (f !== undefined) {
2624
2649
  if (!existsSync(f)) bail("E_BAD_ARGS", `--trigger-event not found: ${f}`);
2625
2650
  try { triggerEvent = JSON.parse(readFileSync(f, "utf8")); } catch (e) { bail("E_BAD_ARGS", `--trigger-event is not valid JSON: ${e.message}`); }
2626
- const ok = triggerEvent && typeof triggerEvent === "object" && !Array.isArray(triggerEvent) && typeof triggerEvent.trigger === "string" && typeof triggerEvent.source === "string" && typeof triggerEvent.repo === "string" && Number.isInteger(triggerEvent.number) && typeof triggerEvent.event === "string";
2627
- if (!ok) bail("E_BAD_ARGS", "--trigger-event must hold { trigger, source, repo, number, url, event, headSha, labels, observedAt }");
2651
+ // A pull-request event names its repo and number; a capability source's, its subject and key,
2652
+ // and its fields, recorded in instance.json, are a plain object of strings.
2653
+ const stringMap = (v) => v !== null && typeof v === "object" && !Array.isArray(v) && Object.values(v).every((x) => typeof x === "string");
2654
+ const ok = triggerEvent && typeof triggerEvent === "object" && !Array.isArray(triggerEvent) && typeof triggerEvent.trigger === "string" && typeof triggerEvent.source === "string" && typeof triggerEvent.event === "string"
2655
+ && (triggerEvent.source === "github.pull_request" ? typeof triggerEvent.repo === "string" && Number.isInteger(triggerEvent.number)
2656
+ : typeof triggerEvent.subject === "string" && typeof triggerEvent.key === "string" && (triggerEvent.fields === undefined || stringMap(triggerEvent.fields)));
2657
+ if (!ok) bail("E_BAD_ARGS", "--trigger-event must hold { trigger, source, repo, number, url, event, headSha, labels, observedAt } (github.pull_request) or { trigger, source, subject, event, key, url?, fields, observedAt } (a capability source; fields an object of strings)");
2628
2658
  } }
2629
2659
  const relativeRoot = flag("relative-root");
2630
2660
  if (relativeRoot !== undefined && (relativeRoot === true || !String(relativeRoot).trim())) bail("E_BAD_ARGS", "--relative-root needs an agents-root path");
@@ -3031,13 +3061,24 @@ async function triggerCmd() {
3031
3061
  const sub = args[1];
3032
3062
  const id = args[2] && !args[2].startsWith("--") ? args[2] : undefined;
3033
3063
  const T = await import("../lib/triggers.mjs");
3064
+ const { REFUSED_TEXT, safeText } = await import("../lib/refused-text.mjs");
3034
3065
  let scope;
3035
3066
  const ws = () => (scope ??= scheduleScopeOf(dirFlag()));
3036
- const out = (result, text) => { if (JSON_MODE) jsonOk(result); else console.log(text ? text(result) : JSON.stringify(result, null, 2)); };
3067
+ // A stored definition that fails validation is still listed and shown, as it was written: what a
3068
+ // terminal gets of it never carries a refused character. In a row's text it is replaced (`shown`);
3069
+ // in the JSON `show` prints as text it is escaped (\uXXXX; the layout's own newlines stay), so the document's value is unchanged.
3070
+ const shown = (v, max) => safeText(typeof v === "string" ? v : JSON.stringify(v) ?? String(v), max);
3071
+ const escaped = (json) => json.replace(new RegExp(REFUSED_TEXT.source, "gu"), (c) => (c === "\n" ? c : Array.from({ length: c.length }, (_, i) => `\\u${c.charCodeAt(i).toString(16).padStart(4, "0")}`).join("")));
3072
+ const out = (result, text) => { if (JSON_MODE) jsonOk(result); else console.log(text ? text(result) : escaped(JSON.stringify(result, null, 2))); };
3037
3073
  const needId = () => { if (!id) throw T.triggerError("E_BAD_ARGS", `oats trigger ${sub} <id>`); return id; };
3038
- const usage = "usage: oats trigger add (--file <trigger.json> | --from <package>:<template> [--set <name>=<value>]… [--id <id>]) [--description=<text>] [--workspace <member> --runs-on <host> --owner <host>/<login>] | update <id> --description=<text> | list | show <id> | enable <id> | disable <id> | remove <id> | test <id> | status [<id>] [--dir <deployment>] [--json] (<id>: local/<id> or <member>/<id>)";
3074
+ const usage = "usage: oats trigger add (--file <trigger.json> | --from <package>:<template> [--set <name>=<value>]… [--id <id>]) [--description=<text>] [--workspace <member> --runs-on <host> --owner <host>/<login>] | update <id> --description=<text> | list | show <id> | enable <id> | disable <id> | remove <id> | test <id> [--run-source] | poll <id> --run-source [--max-age <s>] | status [<id>] [--dir <deployment>] [--json] (<id>: local/<id> or <member>/<id>; --run-source: run a capability source's command on this host, which test and poll do only when asked)";
3039
3075
  const where = (t) => (t.origin?.kind === "workspace" ? (t.runsHere ? `runs here as ${t.owner}` : `${t.reason === "assigned-elsewhere" ? `runs on ${t.runsOn}` : t.reason ?? "disabled here"}`) : t.enabledHere ? "local" : "local, disabled");
3040
- const line = (t) => `${t.id} ${where(t)} ${t.on?.source ?? "?"} ${t.on?.repo ?? "?"} [${(t.on?.events || []).join(",")}]${t.on?.labels?.length ? ` labels ${t.on.labels.join(",")}` : ""} every ${t.on?.poll ?? "?"} → spawn ${t.spawn?.soul ?? "?"}${t.spawn?.teams?.length ? ` in ${t.spawn.teams.join(",")}` : ""}${t.invalid ? ` INVALID: ${t.invalid.message}` : ""}`;
3076
+ // A capability source names its params where the built-in names its repository.
3077
+ const watched = (on) => (T.isCapabilitySource(on?.source) ? `${on.source}${Object.keys(on.params || {}).length ? ` ${Object.entries(on.params).map(([k, v]) => `${shown(k, 40)}=${shown(v, 200)}`).join(" ")}` : ""}` : `${on?.source ?? "?"} ${on?.repo ?? "?"}`);
3078
+ // One row, one line, whatever an invalid stored definition holds (its id, labels and soul are as written too).
3079
+ const line = (t) => safeText(`${t.id} ${where(t)} ${watched(t.on)} [${T.isCapabilitySource(t.on?.source) ? shown((t.on?.events || []).join(","), 700) : (t.on?.events || []).join(",")}]${t.on?.labels?.length ? ` labels ${t.on.labels.join(",")}` : ""} every ${t.on?.poll ?? "?"} → spawn ${t.spawn?.soul ?? "?"}${t.spawn?.teams?.length ? ` in ${t.spawn.teams.join(",")}` : ""}${t.invalid ? ` INVALID: ${t.invalid.message}` : ""}`, 8000);
3080
+ // A source's own words are printed only under this label, never as the kernel's (docs/schedules.md).
3081
+ const said = (x) => (x ? `source says: ${x.code}${x.message ? `: ${x.message}` : ""}` : "");
3041
3082
  // The workspace automations of this deployment (the snapshot) placed on this host.
3042
3083
  let actx;
3043
3084
  const ctx = () => (actx ??= scopeAutomations(ws(), {}));
@@ -3065,7 +3106,31 @@ async function triggerCmd() {
3065
3106
  return out({ trigger: T.updateTriggerDescription(ws(), needId(), description, ctx()) }, (r) => line(r.trigger));
3066
3107
  }
3067
3108
  case "remove": return out(T.removeTrigger(ws(), needId(), ctx()), (r) => `removed trigger ${r.removed}${r.live.length ? ` (its live instances keep running: ${r.live.join(", ")})` : ""}`);
3068
- case "status": return out(T.triggerStatus(ws(), id, ctx()), (r) => r.triggers.map((t) => `${t.id} last poll ${t.lastPoll ? `${t.lastPoll.at} ${t.lastPoll.ok ? `ok (${t.lastPoll.matching}/${t.lastPoll.prs} PRs match)` : `FAILED: ${t.lastPoll.error}`}` : "never"} pending ${t.pending.length} fired ${t.firedTotal} live ${t.live.map((l) => l.instance).join(",") || "none"}${t.lastError ? `\n last error ${t.lastError.at}: ${t.lastError.message}` : ""}`).join("\n") || "(no triggers)");
3109
+ case "status": return out(T.triggerStatus(ws(), id, ctx()), (r) => r.triggers.map((t) => {
3110
+ if (!t.source) return `${t.id} last poll ${t.lastPoll ? `${t.lastPoll.at} ${t.lastPoll.ok ? `ok (${t.lastPoll.matching}/${t.lastPoll.prs} PRs match)` : `FAILED: ${t.lastPoll.error}`}` : "never"} pending ${t.pending.length} fired ${t.firedTotal} live ${t.live.map((l) => l.instance).join(",") || "none"}${t.lastError ? `\n last error ${t.lastError.at}: ${t.lastError.message}` : ""}`;
3111
+ const lp = t.lastPoll;
3112
+ return [`${t.id} source ${t.source.capability}:${t.source.name} last poll ${lp ? `${lp.at} ${lp.ok ? `ok (${lp.events} events, ${lp.invalidEvents} invalid, ${lp.skipped} skipped, ${lp.filtered} filtered)` : `FAILED (${lp.cause ?? "?"}): ${lp.error}`}` : "never"} pending ${t.pending.length} fired ${t.firedTotal} live ${t.live.map((l) => l.instance).join(",") || "none"}`,
3113
+ ...(t.invalid ? [` INVALID ${t.invalid.at}: ${t.invalid.code}: ${t.invalid.message}`] : []),
3114
+ ...(lp && !lp.ok && lp.source ? [` ${said(lp.source)}`] : []),
3115
+ ...t.invalidEvents.map((x) => ` invalid event (${x.rule}): ${x.text}`),
3116
+ ...t.skipped.map((x) => ` skipped ${x.subject}, source says: ${x.why}`),
3117
+ ...(t.lastError && !t.invalid ? [` last error ${t.lastError.at}: ${t.lastError.message}`] : [])].join("\n");
3118
+ }).join("\n") || "(no triggers)");
3119
+ case "poll": {
3120
+ // Runs the capability's source command now (records nothing, spawns nothing), and so only with
3121
+ // --run-source: the caller's intent, never trust consent (the tick's child passes it). The tick's own
3122
+ // child gets OATS_TRIGGER_POLL_DEADLINE (epoch ms; internal between the tick and its child,
3123
+ // not a contract): its source gets only what is left before it (lib/triggers.mjs pollViaChild).
3124
+ const raw = process.env.OATS_TRIGGER_POLL_DEADLINE;
3125
+ const deadline = raw && /^\d+$/.test(raw) ? Number(raw) : null;
3126
+ const r = await T.pollSource(ws(), needId(), { ctx: ctx(), remoteOptions: remoteOptionsFromEnv(), deadline, runSource: args.includes(T.RUN_SOURCE_FLAG) });
3127
+ if (JSON_MODE) { jsonOk(withObservation(r)); return; }
3128
+ return out(r, (x) => [`trigger ${x.id}: ${x.source.capability}:${x.source.name} listed ${x.events.length} event(s) (nothing recorded, nothing spawned)`,
3129
+ ...x.events.map((ev) => ` ${ev.event} ${ev.subject} ${ev.key}`),
3130
+ ...(x.filtered ? [` ${x.filtered} filtered (events the trigger does not select)`] : []),
3131
+ ...x.invalidEvents.map((v) => ` invalid event (${v.rule}): ${v.text}`),
3132
+ ...x.skipped.map((k) => ` skipped ${k.subject}, source says: ${k.why}`)].join("\n"));
3133
+ }
3069
3134
  case "test": {
3070
3135
  let workspaceTeams = null;
3071
3136
  try {
@@ -3075,7 +3140,23 @@ async function triggerCmd() {
3075
3140
  const shared = typeof local.workspace === "string" && !local.standalone ? (await observeWorkspace(local.workspace, { remoteOptions: remoteOptionsFromEnv() })).workspace : null;
3076
3141
  workspaceTeams = [...teamModel(shared, local).labels.keys()];
3077
3142
  } catch { /* reported as unknown (null) */ }
3078
- return out(T.testTrigger(ws(), needId(), { workspaceTeams, ctx: ctx() }), (r) => [
3143
+ // --run-source: a capability source's command runs only when asked (inert for the built-in).
3144
+ const tested = await T.testTrigger(ws(), needId(), { workspaceTeams, ctx: ctx(), remoteOptions: remoteOptionsFromEnv(), runSource: args.includes(T.RUN_SOURCE_FLAG) });
3145
+ if (tested.source) return out(tested, (r) => [
3146
+ `trigger ${r.id}: ${r.ok ? "ready" : "NOT ready"} (${r.source.invalid || r.source.cause === "resolution" ? "the source did not run" : "the source ran"}; nothing was recorded or spawned)`,
3147
+ ` placement ${r.placement.runsOn ? `runs on ${r.placement.runsOn} as ${r.placement.owner}; this host is ${r.placement.host ?? "(unnamed)"} — ${r.placement.runsHere ? "runs here" : r.placement.reason ?? "disabled here"}` : "local (this host)"}`,
3148
+ ...(r.gh ? [` gh auth ${r.gh.ok ? `ok — ${r.gh.account ?? "?"} via ${r.gh.credentialSource}` : `FAILED${r.gh.detail ? ` — ${r.gh.detail}` : ""}`}`] : []),
3149
+ ` source ${r.source.capability}:${r.source.name} ${r.source.ok ? `listed ${r.source.events.length} event(s), ${r.source.invalidEvents.length} invalid, ${r.source.skipped.length} skipped, ${r.source.filtered} filtered` : r.source.invalid ? `INVALID: ${r.source.invalid.message}` : `FAILED (${r.source.cause ?? "?"}): ${r.source.error.message}`}`,
3150
+ ...(r.source.source ? [` ${said(r.source.source)}`] : []),
3151
+ ...r.source.invalidEvents.map((v) => ` invalid (${v.rule}) ${v.text}`),
3152
+ ...r.source.skipped.map((k) => ` skipped ${k.subject}, source says: ${k.why}`),
3153
+ ` soul ${r.soul.name} ${r.soul.resolves ? `resolves${r.soul.messaging ? ` (messaging ${r.soul.messaging})` : ""}` : `does NOT resolve: ${r.soul.error.code} ${r.soul.error.message}`}`,
3154
+ ` teams ${r.teams.requested.join(", ") || "(none)"}${r.teams.undeclared?.length ? ` undeclared: ${r.teams.undeclared.join(", ")}` : ""}`,
3155
+ ` would fire ${r.wouldFire.length ? r.wouldFire.map((w) => `${w.event} ${w.subject}${w.instance ? ` as ${w.instance}` : ""}${w.held ? ` (held: ${w.held})` : ""}`).join(", ") : "nothing now"}`,
3156
+ ...r.problems.map((p) => ` problem ${p}`),
3157
+ ...(r.warnings ?? []).map((w) => ` warning ${w}`),
3158
+ ].join("\n"));
3159
+ return out(tested, (r) => [
3079
3160
  `trigger ${r.id}: ${r.ok ? "ready" : "NOT ready"} (nothing was spawned)`,
3080
3161
  ` placement ${r.placement.runsOn ? `runs on ${r.placement.runsOn} as ${r.placement.owner}; this host is ${r.placement.host ?? "(unnamed)"} — ${r.placement.runsHere ? "runs here" : r.placement.reason ?? "disabled here"}` : "local (this host)"}`,
3081
3162
  ` gh auth ${r.gh.ok ? `ok — ${r.gh.account ?? "?"} via ${r.gh.credentialSource}` : `FAILED${r.gh.detail ? ` — ${r.gh.detail}` : ""}`}`,
@@ -3118,7 +3199,9 @@ async function triggerCmd() {
3118
3199
  return out(r, printWorkspaceAdd);
3119
3200
  }
3120
3201
  if (spec === undefined) spec = await triggerFromPackage(T, String(from), sets, idFlag);
3121
- return out({ trigger: T.addTrigger(ws(), withDescription(spec, description)) }, (r) => `added ${line(r.trigger)}\n(\`oats trigger test ${r.trigger.id}\` checks gh, the repository, the soul and the teams on this host)`);
3202
+ // A capability source's meaning needs the soul's resolution (asynchronous, so here, before the write).
3203
+ await T.checkAddMeaning(ws(), T.validateTrigger({ ...spec, kind: spec?.kind ?? "trigger" }), { remoteOptions: remoteOptionsFromEnv() });
3204
+ return out({ trigger: T.addTrigger(ws(), withDescription(spec, description)) }, (r) => `added ${line(r.trigger)}\n(\`oats trigger test ${r.trigger.id}${T.isCapabilitySource(r.trigger.on?.source) ? ` ${T.RUN_SOURCE_FLAG}\` runs ${r.trigger.on.source}'s source command on this host and checks the soul and the teams)` : "` checks gh, the repository, the soul and the teams on this host)"}`);
3122
3205
  }
3123
3206
  default: throw T.triggerError("E_BAD_ARGS", usage);
3124
3207
  }
@@ -4335,9 +4418,12 @@ Usage:
4335
4418
  oats schedule add|update <id> … --description=<text> a one-line summary (1-200 characters)
4336
4419
  oats schedule update <id> --description=<text> change only it (--description= clears it)
4337
4420
  oats trigger add (--file <json> | --from <package>:<template> [--set k=v]) | list | show | enable
4338
- | disable | remove <id> | test <id> | status [<id>] event-driven spawns (github.pull_request
4339
- polled with the host's gh by the schedule tick;
4340
- see docs/schedules.md#triggers)
4421
+ | disable | remove <id> | test <id> | poll <id> | status [<id>] event-driven spawns, polled
4422
+ by the schedule tick: github.pull_request (the
4423
+ host's gh) or a capability's <capability>:<source>;
4424
+ see docs/schedules.md#triggers
4425
+ oats trigger test|poll <id> --run-source run a capability source's command on this host: by
4426
+ hand, test and poll do it only when asked
4341
4427
  oats trigger add … --description=<text> a one-line summary (1-200 characters)
4342
4428
  oats trigger update <id> --description=<text> change only it (--description= clears it)
4343
4429
  oats trigger|schedule add … --workspace <member> --runs-on <host> --owner <host>/<login>
@@ -353,6 +353,9 @@ A self-contained package has an `oats.json`:
353
353
  separate from declaring the package.
354
354
  - `environment` lists the exact launch variables the capability may set;
355
355
  spawn hook output must be a subset and use the capability vendor prefix.
356
+ - `triggerSources` (optional) declares the capability's
357
+ [trigger sources](#trigger-sources-triggersources). It is checked only
358
+ where a source is used, never when the capability loads.
356
359
  - Target names never appear in a package manifest.
357
360
 
358
361
  `capability` is the only manifest identity field; it may also carry
@@ -1264,3 +1267,169 @@ checks in one readiness read share 60 s, and checks the budget does not reach
1264
1267
  are not run (`unknown`, `time-budget-exhausted`). Answer from configuration
1265
1268
  and local state. A provider that must call a remote service should bound that
1266
1269
  call well inside the 30 s.
1270
+
1271
+ ## Trigger sources (`triggerSources`)
1272
+
1273
+ A capability may declare **trigger sources**: each is one of its own commands
1274
+ that, at each poll, lists the events that are due now. A
1275
+ [trigger](schedules.md#capability-sources) names one as `on.source:
1276
+ "<capability>:<source>"`, and the kernel keeps everything after the list:
1277
+ event keys, at-least-once recording, pending events, concurrency, the
1278
+ instance name, the event file and the spawn.
1279
+
1280
+ ```json
1281
+ "commands": { "review-source": "bin/graph.mjs review-source" },
1282
+ "triggerSources": {
1283
+ "harvest-branches": {
1284
+ "command": "review-source",
1285
+ "description": "Ready harvest/* branches, one event per judged head",
1286
+ "events": ["opened", "updated"],
1287
+ "parameters": { "prefix": { "default": "harvest/", "description": "Branch prefix", "pattern": "^[A-Za-z0-9._/-]{1,80}$" } },
1288
+ "fields": { "graph": { "pattern": "^[a-z0-9-]{1,40}$" }, "branch": {} },
1289
+ "urlHosts": ["graph.example.org"]
1290
+ }
1291
+ }
1292
+ ```
1293
+
1294
+ - **The source name** is 1 to 40 lowercase letters, digits and dashes,
1295
+ starting with a letter or digit. At most 16 sources.
1296
+ - **`command`** names one of `commands`. Its script must resolve to a regular
1297
+ file inside the module directory.
1298
+ - **`description`** (optional): one line of at most 200 characters.
1299
+ - **`events`**: 1 to 16 distinct names, each 1 to 40 lowercase letters,
1300
+ digits and underscores, starting with a letter.
1301
+ - **`parameters`** (optional, at most 16), named with a letter then letters,
1302
+ digits and underscores (at most 40): `{ required?, default?, description?,
1303
+ pattern? }`. A value is a string of at most 200 characters matching
1304
+ `pattern`, by default `^[A-Za-z0-9._/:@ ,*-]{0,200}$`; a `default` must
1305
+ match it too. Parameters reach the source only, never a task.
1306
+ - **`fields`** (optional, at most 16, named as parameters): `{ pattern? }`, by
1307
+ default `^[A-Za-z0-9._/:@-]{1,200}$`. A trigger's template may name a
1308
+ declared field as `{fields.<name>}`; the value is the event's, validated.
1309
+ Whatever the pattern admits (`.*` included), a value longer than 200
1310
+ characters (code points), or carrying a control character, a line or
1311
+ paragraph separator, a bidi control, U+200B, U+2060, U+FEFF or a tag
1312
+ character, makes its event invalid, and the pattern is never run on one.
1313
+ - **Patterns** are JavaScript regular expressions with the `u` flag (the flag
1314
+ JSON Schema's `pattern` uses), compiled once and always matched whole: the
1315
+ kernel wraps each as `^(?:…)$`. One that does not compile makes the source
1316
+ malformed.
1317
+ - **`urlHosts`** (optional, at most 16): the exact lowercase hostnames an
1318
+ event's `url` may name. With none declared, an event's `url` is invalid.
1319
+ The allow-list lives here, never on an event. An event's `url` must also be
1320
+ printable ASCII with no space (`0x21`–`0x7e`) as written: percent-encode
1321
+ anything else.
1322
+
1323
+ **Containment.** A malformed `triggerSources` **never refuses the
1324
+ capability**. It is not part of the manifest contract that spawn, discovery
1325
+ and the lock check: they ignore it. It is validated only where a source is
1326
+ used, by `trigger add`, a poll, `trigger test` and `trigger poll`, **per
1327
+ source**: a malformed source fails only the triggers naming it
1328
+ (`E_TRIGGER_SOURCE`, `details: { capability, source, pointer }`, the pointer
1329
+ into the manifest), and a well-formed sibling keeps working. A malformed top
1330
+ level (not an object, or more than 16 sources) fails every trigger naming the
1331
+ capability. `oats capabilities show <name> --json` adds `triggerSources`,
1332
+ exactly as declared, and, when the declaration has any, the problems a trigger
1333
+ would get as `triggerSourceProblems: [{ source, pointer, message }]`
1334
+ (`source` `null` for the top level); it never refuses the command. The
1335
+ closed sub-schema is in
1336
+ [`capability-manifest.schema.json`](capability-manifest.schema.json); what a
1337
+ schema cannot say (a pattern compiles, `command` names a command, a default
1338
+ matches its pattern) is checked at use only.
1339
+
1340
+ **Schema tooling.** The runtime ignores manifest keys it does not know, but
1341
+ until this release the published `capability-manifest.schema.json` was closed
1342
+ at the top level (`additionalProperties: false`). A tool validating a manifest
1343
+ against an older copy of the schema flags `triggerSources`: the repository's
1344
+ own `validate-project`, the package dry-run checks, a provider's CI that pins
1345
+ the schema. Validate against this release's schema, or declare the key once
1346
+ your tooling uses it. A provider declaring `triggerSources` does not need to
1347
+ raise `compatibility.oats`: every workspace-model kernel ignores the key, and
1348
+ only the host that runs a trigger naming the source needs this release.
1349
+
1350
+ **Invocation.** A poll runs the command's script with `node`, from the
1351
+ capability's directory in the deployment's verified module store (the
1352
+ capability at its resolved commit, digest-verified, for a member capability
1353
+ as for a package one), with the command's words after the script as
1354
+ arguments and no shell. The host tick runs it through a child `oats trigger
1355
+ poll <id> --run-source --max-age 600`; a person, through `oats trigger poll
1356
+ <id> --run-source` or `oats trigger test <id> --run-source`. Those
1357
+ **execute the capability's source command** whatever the host's trust and
1358
+ the trigger's `runsOn` say, and so only with `--run-source`: without it they
1359
+ are refused (`E_TRIGGER_SOURCE_RUN`) before anything of the capability runs
1360
+ or is written. The flag is caller intent, never trust consent: see
1361
+ [schedules.md](schedules.md#capability-sources). A poll records nothing on
1362
+ its own; the tick records what it folds.
1363
+
1364
+ **Request** — one JSON document on stdin, with exactly these keys:
1365
+
1366
+ ```json
1367
+ {"schemaVersion":1,"phase":"poll","capability":"acme.graph","source":"harvest-branches","trigger":"local/harvest-review",
1368
+ "params":{"prefix":"harvest/"},"settings":{"store":"~/.graph"},
1369
+ "input":{"context":{"kind":"workspace","workspace":"github.com/acme/agents","deployment":"/srv/acme",
1370
+ "soul":"graph-reviewer","host":"kb-bot-server"}}}
1371
+ ```
1372
+
1373
+ - `trigger` is the qualified trigger id.
1374
+ - `params` are the trigger's, with the declared defaults applied (a parameter
1375
+ with neither a value nor a default is absent).
1376
+ - `settings` is the merged provider payload the trigger's soul resolves for
1377
+ the capability.
1378
+ - `host` is this host's `host.name`, or `null`.
1379
+
1380
+ **Environment:** the one a `--soul` [readiness check](#readiness-check-bindingcheck)
1381
+ gets, for the trigger's soul: every ambient `OATS_*`, `OAS_*` and `PI_*`
1382
+ variable removed, the rest inherited, and the kernel's `OATS_CAPABILITY`,
1383
+ `OATS_SETTINGS`, `OATS_SETTINGS_ORIGINS`, `OATS_CLI_BIN`, `OATS_WORKSPACE`,
1384
+ the team variables, `OATS_AGENT`, `OATS_SOUL_ID` and `OATS_SOUL`. There is no
1385
+ `OATS_INSTANCE` or `OATS_INSTANCE_HOME`, and the kernel passes no credential.
1386
+ Under the host timer, the inherited environment is the timer's (only `PATH`
1387
+ and `OATS_HOME_DIR`): keep the source's login in its own store under `HOME`,
1388
+ not in an exported variable.
1389
+
1390
+ **Answer** — exit 0, and exactly one JSON document on stdout, at most 1 MiB
1391
+ (whitespace around it is fine; progress text is not):
1392
+
1393
+ ```json
1394
+ {"schemaVersion":1,"phase":"poll","capability":"acme.graph","source":"harvest-branches","ok":true,
1395
+ "result":{"events":[{"key":"harvest/x:9f2c41d","subject":"harvest/x","event":"opened",
1396
+ "url":"https://graph.example.org/x","fields":{"graph":"kb","branch":"harvest/x"}}],
1397
+ "skipped":[{"subject":"harvest/y","why":"not judged yet"}]}}
1398
+ ```
1399
+
1400
+ - **The envelope** has exactly `schemaVersion, phase, capability, source, ok,
1401
+ result`; `schemaVersion`, `phase`, `capability` and `source` echo the
1402
+ request. `result` is `{ events, skipped? }`, exactly.
1403
+ - **A refusal** is `{…, "ok": false, "error": { "code", "message"? }}`.
1404
+ - **An event** is `{ key, subject, event, url?, fields? }`: the rules are in
1405
+ [schedules.md](schedules.md#capability-sources). An invalid event is
1406
+ dropped alone; the others go on.
1407
+ - **`skipped`** (optional) is `[{ subject, why }]`: what the source looked at
1408
+ and chose not to list, shown in `trigger status` and `trigger test`.
1409
+
1410
+ | Outcome | `E_TRIGGER_POLL` `details.cause` | recorded |
1411
+ |---|---|---|
1412
+ | nonzero exit or a signal | `exit` | nothing; pending events kept |
1413
+ | not exactly one JSON document, unknown keys, a wrong echo, a malformed `result`, over 1 MiB | `result` | nothing |
1414
+ | more than 500 events, or more than 100 skipped | `too-many-events` | nothing |
1415
+ | over 30 s (killed) | `timeout` | nothing |
1416
+ | `ok: false` | `refused`, with `details.source: { code, message? }` | nothing |
1417
+ | the soul does not resolve | `resolution` | nothing |
1418
+ | the trigger's meaning does not hold | (`E_TRIGGER_SOURCE` / `E_TRIGGER_INVALID`) | nothing; the source does not run |
1419
+
1420
+ **Your text is untrusted.** A skipped item's `why`, a refusal's `message` and
1421
+ its `code` are never composed into a task or any kernel sentence. They are
1422
+ kept only in fields that name the source and printed under `source says:`,
1423
+ capped (`why` 200 characters, `message` 500, `code` 128) and with every
1424
+ control character, line or paragraph separator, bidi control, U+200B,
1425
+ U+2060, U+FEFF and tag character replaced by U+FFFD. What a task may carry
1426
+ (`{subject}`, `{key}`, `{url}`, `{fields.<name>}`) is refused rather than
1427
+ replaced: an event whose `url` is not printable ASCII, or whose field value
1428
+ is longer than 200 characters or carries one of those characters whatever
1429
+ its pattern admits, is an invalid event.
1430
+
1431
+ **Time.** A source gets at most 30 s and is killed after that; the tick's
1432
+ whole poll, resolution included, gets 35 s, and polls run only while they can
1433
+ end within 50 s of the tick's start. Answer from a cache or a quick query: a
1434
+ source slower than that should cache.
1435
+
@@ -248,6 +248,48 @@
248
248
  }
249
249
  }
250
250
  },
251
+ "triggerSources": {
252
+ "description": "Trigger sources (#669): each a command of this capability that, at each poll, lists the events due now; a trigger names one as on.source \"<capability>:<source>\". Validated only where a source is used (trigger add, a poll, trigger test and trigger poll), never when the capability loads: a malformed declaration fails the triggers naming it (E_TRIGGER_SOURCE) and nothing else. Checked at use only, not by this schema: every pattern compiles; command names a key of commands; a parameter default matches its pattern. A pattern is ECMA-262 with the u flag, matched anchored as ^(?:…)$; the default parameter value pattern is ^[A-Za-z0-9._/:@ ,*-]{0,200}$ and the default field pattern ^[A-Za-z0-9._/:@-]{1,200}$. Whatever its pattern admits, an event's field value is at most 200 code points and carries no control, bidi, invisible or tag character.",
253
+ "type": "object",
254
+ "maxProperties": 16,
255
+ "propertyNames": { "pattern": "^[a-z0-9][a-z0-9-]{0,39}$" },
256
+ "additionalProperties": {
257
+ "type": "object",
258
+ "required": ["command", "events"],
259
+ "additionalProperties": false,
260
+ "properties": {
261
+ "command": { "type": "string", "pattern": "^[a-z0-9][a-z0-9-]*$", "description": "One of this manifest's commands: the source's program, run once per poll (one JSON request on stdin, one JSON answer on stdout)." },
262
+ "description": { "type": "string", "maxLength": 200, "pattern": "^[^\\u0000-\\u001f\\u007f-\\u009f\\u2028\\u2029]*$" },
263
+ "events": { "type": "array", "minItems": 1, "maxItems": 16, "uniqueItems": true, "items": { "type": "string", "pattern": "^[a-z][a-z0-9_]{0,39}$" } },
264
+ "parameters": {
265
+ "type": "object",
266
+ "maxProperties": 16,
267
+ "propertyNames": { "pattern": "^[a-zA-Z][a-zA-Z0-9_]{0,39}$" },
268
+ "additionalProperties": {
269
+ "type": "object",
270
+ "additionalProperties": false,
271
+ "properties": {
272
+ "required": { "type": "boolean" },
273
+ "default": { "type": "string", "maxLength": 200 },
274
+ "description": { "type": "string", "maxLength": 200, "pattern": "^[^\\u0000-\\u001f\\u007f-\\u009f\\u2028\\u2029]*$" },
275
+ "pattern": { "type": "string", "minLength": 1 }
276
+ }
277
+ }
278
+ },
279
+ "fields": {
280
+ "type": "object",
281
+ "maxProperties": 16,
282
+ "propertyNames": { "pattern": "^[a-zA-Z][a-zA-Z0-9_]{0,39}$" },
283
+ "additionalProperties": {
284
+ "type": "object",
285
+ "additionalProperties": false,
286
+ "properties": { "pattern": { "type": "string", "minLength": 1 } }
287
+ }
288
+ },
289
+ "urlHosts": { "type": "array", "maxItems": 16, "uniqueItems": true, "items": { "type": "string", "maxLength": 253, "pattern": "^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?(?:\\.[a-z0-9](?:[a-z0-9-]*[a-z0-9])?)*$" } }
290
+ }
291
+ }
292
+ },
251
293
  "hooks": {
252
294
  "type": "object",
253
295
  "properties": {
@@ -78,6 +78,98 @@ Which teams a soul may join, and its default, are committed in the workspace's
78
78
  commit instead). How teams are resolved, and what a messaging provider does
79
79
  with them, is in [workspaces.md](workspaces.md#teams).
80
80
 
81
+ ## Claude channel delivery: the approved route
82
+
83
+ Claude seats on aweb channel delivery start without Claude's “WARNING:
84
+ Loading development channels” prompt through the **approved route**: the
85
+ `oats.aweb` setting `claudeChannelMode: approved` starts Claude with
86
+ `--channels plugin:aweb-channel@awebai-marketplace`, and Claude shows no
87
+ development prompt. Claude admits the plugin when a root-owned machine
88
+ managed-settings file lists it. The route does not depend on the Claude
89
+ version and needs no OATS mechanism beyond these settings. The operator's
90
+ ordered procedure is the `oats.setup` host step “Claude channel delivery
91
+ (approved route)” in `/oats-workspace-config`, which `/oats-onboarding` card 4
92
+ calls; the provider's side is `/oats-aweb` §4.
93
+
94
+ **The managed-settings file** is a host change made by a human admin with
95
+ sudo. OATS never writes it.
96
+
97
+ | | |
98
+ |---|---|
99
+ | Location | Linux: `/etc/claude-code/managed-settings.json`; macOS: `/Library/Application Support/ClaudeCode/managed-settings.json` |
100
+ | Owner and mode | root, `0644` |
101
+ | Content | exactly `{"channelsEnabled": true, "allowedChannelPlugins": [{"plugin": "aweb-channel", "marketplace": "awebai-marketplace"}]}` |
102
+ | Existing file | merge these two keys into it; never overwrite other keys |
103
+ | Drop-ins | Claude also reads `managed-settings.d/*.json` beside the file |
104
+
105
+ Setting `allowedChannelPlugins` **replaces Anthropic's default channel
106
+ allowlist** on that host. That list is the official discord, telegram,
107
+ fakechat and imessage plugins; a host that uses any of them must list them
108
+ too.
109
+
110
+ **Precedence.** Claude reads its managed policy from the first source
111
+ present: server-managed settings (a claude.ai Team/Enterprise organization's
112
+ admin console), then an MDM profile (`com.anthropic.claudecode` on macOS), then
113
+ the file. On an account governed by server-managed settings or MDM the file is
114
+ ignored, and the organization admin sets the same two keys there instead.
115
+ Pro/Max accounts and plain API-key use have no server-managed settings, so the
116
+ file applies. `channelsEnabled: true` is required for API-key users whenever
117
+ any managed policy exists, and for Team/Enterprise subscribers; Pro/Max ignore
118
+ it. It is harmless there: always include it.
119
+
120
+ **OATS side**, in this host's `oats-local.yaml` under `settings.oats.aweb`:
121
+
122
+ ```yaml
123
+ settings:
124
+ oats.aweb:
125
+ claudeChannelMode: approved # host-only
126
+ delivery: channel # host-wide; or per spawn: --provider oats.aweb delivery=channel
127
+ ```
128
+
129
+ With channel delivery, pi uses its `@awebai/pi` extension and Codex always
130
+ uses the host broker.
131
+
132
+ **The plugin.** `aweb-channel` must be installed from the marketplace named
133
+ `awebai-marketplace` (GitHub `awebai/claude-plugins`) and enabled, in the
134
+ Claude config directory the host's Claude launch configuration uses (its
135
+ `CLAUDE_CONFIG_DIR`, else `~/.claude`).
136
+
137
+ **Existing homes** keep the delivery and channel mode recorded at their spawn.
138
+ Respawn a home to adopt the route. Setup never restarts running agents
139
+ without the operator's word.
140
+
141
+ **No launch-prompt opt-in** is needed in approved mode: the
142
+ [exact-home consent](#exact-home-launch-prompt-consent) applies only to
143
+ development mode, and qualifies only Claude 2.1.289 on `darwin-arm64`.
144
+
145
+ **Verify:**
146
+
147
+ 1. `oats spawn <soul> --preview` shows `settings.oats.aweb.claudeChannelMode:
148
+ approved` and `delivery: channel`.
149
+ 2. The started session shows no development prompt, and its banner shows
150
+ “Channels (experimental) messages from plugin:aweb-channel@awebai-marketplace
151
+ inject directly in this session”, followed by “restart without --channels
152
+ to stop”. At normal terminal widths the banner wraps over two rows: look
153
+ for each part, not for one string.
154
+ 3. The banner says none of `not on the approved channels allowlist`,
155
+ `not on your org's approved channels list`, `blocked by org policy` or
156
+ `plugin not installed`.
157
+ 4. Receive is proven only by the `/oats-aweb` nonce exchange.
158
+
159
+ **Failure banners**, their cause and remedy:
160
+
161
+ | What the session shows | Cause | Remedy |
162
+ |---|---|---|
163
+ | `not on the approved channels allowlist` | the effective managed policy has no `allowedChannelPlugins` (no file, the file not read, or the key missing), so Anthropic's default list applied | write or fix the file |
164
+ | `not on your org's approved channels list` | the effective policy has an `allowedChannelPlugins` without this plugin and marketplace pair: the names in the file are wrong, or a higher source (server-managed settings or MDM) supplies its own list | fix the entry, or have the organization admin add it |
165
+ | `blocked by org policy` (then “Inbound messages will be silently dropped”) | the effective policy lacks `channelsEnabled: true`, which Team/Enterprise subscribers need, and API-key use whenever any managed policy exists | add the key, or have the organization admin set it |
166
+ | `plugin:aweb-channel@awebai-marketplace · plugin not installed` | the plugin is not installed in the launch's Claude config directory | install and enable it there |
167
+ | the development prompt still appears | the home started in development mode, not approved: the host setting is missing, or the home was spawned before the change | set `claudeChannelMode: approved`, then respawn the home |
168
+
169
+ **Limits.** Channels are an Anthropic research preview. Anthropic's
170
+ account-level feature flag gates channels on every route. The allowlist
171
+ matches the marketplace by name.
172
+
81
173
  ## Exact-home launch prompt consent
82
174
 
83
175
  `launchPromptAnswers` belongs only in the host's `oats-local.yaml`. It is
@@ -114,6 +206,8 @@ selects arguments; it does not grant consent. Approved-mode arguments, another
114
206
  plugin, multiple plugins or contradictory channel arguments cannot qualify.
115
207
  Environment values, spawn flags and saved launch recipes cannot enable consent.
116
208
  Existing harness folder-trust configuration remains independent.
209
+ The version-independent route, with no prompt to answer, is
210
+ [the approved route](#claude-channel-delivery-the-approved-route).
117
211
 
118
212
  Preview reports effective `launchPromptAnswers.awebDevelopmentChannel` and
119
213
  `consentSource` without terminal capture or input. `--no-launch` never answers.
@@ -398,6 +492,9 @@ is safe to delete.
398
492
  - **Per-instance provider facts:** `oats spawn <soul> --provider <cap> key=value`,
399
493
  recorded in the instance's `instance.json`.
400
494
  - **Shared teams, stores and defaults:** the workspace file.
495
+ - **Claude's channel admission:** Claude's own managed policy (server-managed
496
+ settings, an MDM profile or the root-owned managed-settings file; see
497
+ [the approved route](#claude-channel-delivery-the-approved-route)).
401
498
 
402
499
  ## Inspecting the effective configuration
403
500