@aiwg/cli 2026.10.8 → 2026.10.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 (104) hide show
  1. package/agentic/code/providers/model-capabilities.v1.json +197 -3
  2. package/bin/aiwg.mjs +8 -0
  3. package/dist/src/artifacts/cli.js +9 -5
  4. package/dist/src/auth/config.js +3 -8
  5. package/dist/src/auth/resource-credentials.js +35 -2
  6. package/dist/src/cli/handlers/diagnose.js +13 -0
  7. package/dist/src/cli/handlers/mc-admission.js +39 -0
  8. package/dist/src/cli/handlers/mc.js +2 -31
  9. package/dist/src/cli/handlers/models-help.js +52 -0
  10. package/dist/src/cli/handlers/models.js +11 -81
  11. package/dist/src/cli/handlers/resource-versions.js +8 -5
  12. package/dist/src/cli/handlers/script-runner.js +13 -1
  13. package/dist/src/cli/handlers/use-addon-profile.js +72 -0
  14. package/dist/src/cli/handlers/use.js +209 -233
  15. package/dist/src/cli/ui.js +1 -0
  16. package/dist/src/config/aiwg-config.js +38 -184
  17. package/dist/src/config/cli-help.js +54 -0
  18. package/dist/src/config/cli.js +5 -69
  19. package/dist/src/config/config-normalization.js +10 -0
  20. package/dist/src/config/worker-activation-gate.js +26 -0
  21. package/dist/src/config/worker-adoption-cli.js +102 -0
  22. package/dist/src/config/worker-adoption.js +368 -0
  23. package/dist/src/config/worker-config-digest.js +14 -0
  24. package/dist/src/config/worker-group-templates.js +150 -0
  25. package/dist/src/config/worker-guidance-warning.js +28 -0
  26. package/dist/src/config/worker-owner-lock.js +152 -0
  27. package/dist/src/config/worker-parallelism.js +154 -0
  28. package/dist/src/config/worker-write.js +75 -0
  29. package/dist/src/decision/telemetry/exporter.js +2 -1
  30. package/dist/src/decision/telemetry/index.js +1 -0
  31. package/dist/src/decision/telemetry/mapping.js +43 -0
  32. package/dist/src/decision/telemetry/otlp-http.js +5 -2
  33. package/dist/src/decision/telemetry/redaction.js +6 -1
  34. package/dist/src/decision/telemetry/types.js +3 -0
  35. package/dist/src/decision/telemetry/worker.js +69 -0
  36. package/dist/src/lint/rule-activation.js +15 -7
  37. package/dist/src/lint/runner.js +2 -2
  38. package/dist/src/mcp/server.mjs +2 -11
  39. package/dist/src/mcp/stdio-lifecycle.mjs +27 -0
  40. package/dist/src/mcp/tools/worker-failure-diagnostics.mjs +9 -0
  41. package/dist/src/mcp/tools/worker-invoke.mjs +6 -6
  42. package/dist/src/mission-protocol/codecs.js +8 -38
  43. package/dist/src/mission-protocol/worker-contract-diagnostics.js +62 -0
  44. package/dist/src/mission-protocol/worker-invocation-types.js +2 -0
  45. package/dist/src/models/conductor-data-policy.d.mts +8 -0
  46. package/dist/src/models/conductor-data-policy.mjs +190 -0
  47. package/dist/src/models/config-loader.js +19 -3
  48. package/dist/src/models/config-writer.js +27 -0
  49. package/dist/src/models/model-capabilities.v1.json +197 -3
  50. package/dist/src/models/provider-policy.js +7 -155
  51. package/dist/src/models/resolver.js +2 -293
  52. package/dist/src/models/worker-artifact-binding.mjs +12 -0
  53. package/dist/src/models/worker-direct-readiness-policy.js +155 -0
  54. package/dist/src/models/worker-direct-readiness.js +9 -218
  55. package/dist/src/models/worker-health-readiness.js +105 -26
  56. package/dist/src/models/worker-installation.mjs +12 -14
  57. package/dist/src/models/worker-member-references.js +64 -0
  58. package/dist/src/models/worker-plan.js +317 -0
  59. package/dist/src/models/worker-selection-policy.js +217 -0
  60. package/dist/src/models/wrapper-deployment.js +1 -1
  61. package/dist/src/resources/web-release.js +76 -65
  62. package/dist/src/serve/shared-host-admission-checks.js +116 -0
  63. package/dist/src/serve/shared-host-scheduler.js +25 -107
  64. package/dist/src/serve/shared-host-starvation.js +73 -0
  65. package/dist/src/serve/worker-artifacts.d.mts +4 -0
  66. package/dist/src/serve/worker-artifacts.mjs +56 -0
  67. package/dist/src/serve/worker-command-request.js +68 -0
  68. package/dist/src/serve/worker-invocation-paths.js +144 -0
  69. package/dist/src/serve/worker-invocation-preparation.js +169 -0
  70. package/dist/src/serve/worker-invocation.js +24 -291
  71. package/dist/src/serve/worker-stdin-frame.d.mts +2 -2
  72. package/dist/src/serve/worker-stdin-frame.mjs +6 -6
  73. package/dist/src/smiths/context-pipeline/parallelism-section.js +19 -7
  74. package/dist/src/storage/backends/fortemi.js +33 -29
  75. package/dist/src/storage/backends/logseq.js +16 -3
  76. package/dist/src/storage/backends/postgres.js +74 -33
  77. package/dist/src/storage/backends/postgrest.js +37 -13
  78. package/dist/src/storage/config.js +6 -1
  79. package/dist/src/uhp/config.js +4 -0
  80. package/package.json +9 -1
  81. package/schemas/mission-v1.schema.json +20 -19
  82. package/schemas/models/model-config-compatibility.v1.schema.json +16 -0
  83. package/tools/agents/providers/claude-post-deploy.mjs +35 -0
  84. package/tools/agents/providers/claude.mjs +3 -30
  85. package/tools/agents/providers/codex-post-deploy.mjs +13 -0
  86. package/tools/agents/providers/codex.mjs +2 -8
  87. package/tools/agents/providers/conductor-data-guard.mjs +61 -0
  88. package/tools/agents/providers/rule-delivery.mjs +3 -16
  89. package/tools/agents/providers/rule-presentation.mjs +38 -0
  90. package/tools/plugin/package-plugins.mjs +1 -1
  91. package/tools/ralph-external/lib/claude-adapter.mjs +2 -2
  92. package/tools/ralph-external/lib/codex-adapter.mjs +3 -3
  93. package/tools/ralph-external/lib/managed-worker-attempt.mjs +86 -0
  94. package/tools/ralph-external/lib/provider-adapter.mjs +11 -260
  95. package/tools/ralph-external/lib/session-attempt.mjs +85 -0
  96. package/tools/ralph-external/lib/strict-worker-json.mjs +190 -0
  97. package/tools/ralph-external/lib/worker-artifacts.mjs +209 -0
  98. package/tools/ralph-external/lib/worker-final.mjs +143 -0
  99. package/tools/ralph-external/lib/worker-inputs.mjs +55 -0
  100. package/tools/ralph-external/lib/worker-isolation.mjs +2 -44
  101. package/tools/ralph-external/lib/worker-launch-cli.mjs +47 -0
  102. package/tools/ralph-external/lib/worker-native-sandbox.mjs +83 -0
  103. package/tools/ralph-external/session-launcher.mjs +73 -217
  104. package/vscode-extension/schemas/aiwg.config.v1.json +161 -2
@@ -0,0 +1,317 @@
1
+ // Resolves eligible worker tuples against current config, catalog and installation snapshots.
2
+ import { ownWorkerRoleGuidance } from './worker-selection-policy.js';
3
+ import { mergeGroupWorkerPolicy } from '../config/worker-group-templates.js';
4
+ import { WORKER_DISPATCH_ENABLE_COMMAND, WORKER_DISPATCH_READINESS_COMMAND } from './worker-dispatch-offer.js';
5
+ import { resolveWorkerGroupInstallation, resolveParallelism, validateWorkerGroupQualifications, validateWorkerGroupReferences, validateWorkerBudgetEnforcement, workerActivationDigests, workerConfigDigest, } from '../config/aiwg-config.js';
6
+ import { qualifyWorkerInvocationProfile, validateWorkerPolicyRoute, validateWorkerModelObservation, assertWorkerLaunchMode, hasOperatorWorkerNativeRenderer, hasSelectionRelevantConflicts, workerContextHeadroom, workerModelKey, isCanonicalWorkerModelKey, WorkerSelectionPolicySchema, validateWorkerCatalogDiscovery, } from './provider-policy.js';
7
+ import { MODEL_WRAPPERS } from './provider-models.js';
8
+ import { routeModelTier } from './router.js';
9
+ const matchesChoice = (tuple, choice) => tuple.group === choice.group && tuple.member === choice.member && tuple.model === choice.model && tuple.effort === choice.effort;
10
+ function findWorkerModelRow(rows, model) {
11
+ const matches = rows?.filter(row => row.id === model || row.apiModelId === model) ?? [];
12
+ return matches.length === 1 ? matches[0] : undefined;
13
+ }
14
+ function workerCatalogDigest(catalog) {
15
+ if (!catalog.discovery)
16
+ return workerConfigDigest(catalog);
17
+ // Offline loads synthesize fetchedAt. Keep catalog facts and persisted
18
+ // observation/qualification times pinned, independent of the load clock.
19
+ const { fetchedAt, ...discovery } = catalog.discovery;
20
+ return workerConfigDigest({ ...catalog, discovery });
21
+ }
22
+ /** Pure S1 resolution. No probing, launch, activation, admission, or writes.
23
+ * Recheck against freshly loaded snapshots before preparing an invocation. */
24
+ export function resolveWorkerPlan(snapshot, request) {
25
+ let parallelism = snapshot.config.parallelism ?? {};
26
+ const policy = snapshot.models.defaults.workerSelection;
27
+ const digests = {
28
+ ...snapshot.modelDigests,
29
+ configDigest: workerActivationDigests(snapshot.config).configDigest,
30
+ resolvedModelsDigest: workerConfigDigest(snapshot.models),
31
+ catalogDigest: workerCatalogDigest(snapshot.catalog),
32
+ profileDigest: workerConfigDigest([snapshot.registry, snapshot.installations]),
33
+ constraintsDigest: workerConfigDigest(snapshot.constraints),
34
+ };
35
+ const plan = {
36
+ mode: parallelism.worker_mode ?? 'direct', status: 'blocked', role: null, selected: null,
37
+ eligible: [], alternatives: [], exclusions: [], diagnostics: [], digests,
38
+ policy: structuredClone(policy), origins: structuredClone(snapshot.models.workerPolicyOrigins),
39
+ choice: null, capacity: 'conductor-guidance-only', ceilings: {},
40
+ };
41
+ const diagnostic = (code, pointer, message) => ({ code, pointer, message });
42
+ const block = (code, pointer, message) => {
43
+ plan.diagnostics.push(diagnostic(code, pointer, message));
44
+ };
45
+ if (!parallelism.worker_dispatch) {
46
+ plan.status = 'disabled';
47
+ block('OG_CONFIG_REFERENCE', '/parallelism/worker_dispatch', `Direct worker dispatch is off (parallelism.worker_dispatch). Enable with \`${WORKER_DISPATCH_ENABLE_COMMAND}\` `
48
+ + `(then check readiness with \`${WORKER_DISPATCH_READINESS_COMMAND}\`).`);
49
+ return plan;
50
+ }
51
+ const now = new Date(request.now);
52
+ if (!Number.isFinite(now.getTime()))
53
+ block('OG_CONFIG_REFERENCE', '/request/now', 'A valid current clock is required');
54
+ if (!request.context || typeof request.context.estimator !== 'string')
55
+ block('OG_CONFIG_REFERENCE', '/request/context', 'A named, bounded context estimate is required');
56
+ if (snapshot.constraints?.revokedModels?.some(key => !isCanonicalWorkerModelKey(key)))
57
+ block('OG_CONFIG_REFERENCE', '/constraints/revokedModels', 'Revocations require canonical inference model keys');
58
+ if (request.expectedDigests && (Object.keys(request.expectedDigests).length !== Object.keys(digests).length
59
+ || Object.entries(digests).some(([key, value]) => request.expectedDigests[key] !== value))) {
60
+ block('OG_CONFIG_REFERENCE', '/request/expectedDigests', 'Current input digests changed; resolve again');
61
+ }
62
+ if (Object.values(snapshot.modelDigests).length !== 3 || Object.values(digests).some(value => !/^sha256:[a-f0-9]{64}$/.test(value))) {
63
+ block('OG_CONFIG_REFERENCE', '/models', 'Current loader input digests are required');
64
+ }
65
+ if (plan.mode === 'managed') {
66
+ const activation = parallelism.activation;
67
+ if (!activation || ['configDigest', 'projectModelsDigest', 'userModelsDigest', 'builtinModelsDigest'].some(key => activation[key] !== digests[key])) {
68
+ block('OG_CONFIG_REFERENCE', '/parallelism/activation', 'Managed activation is missing or stale');
69
+ }
70
+ }
71
+ if (!policy)
72
+ block('OG_CONFIG_REFERENCE', '/defaults/workerSelection', 'Current merged worker policy is required');
73
+ const catalogErrors = validateWorkerCatalogDiscovery(snapshot.catalog.discovery);
74
+ if (catalogErrors.length)
75
+ block('OG_ADAPTER_UNQUALIFIED', '/catalog/discovery', catalogErrors.join('; '));
76
+ if (plan.diagnostics.length || !policy)
77
+ return plan;
78
+ const policyShape = WorkerSelectionPolicySchema.safeParse(policy);
79
+ if (!policyShape.success) {
80
+ block('OG_CONFIG_REFERENCE', '/defaults/workerSelection', policyShape.error.message);
81
+ return plan;
82
+ }
83
+ for (const message of validateWorkerGroupReferences(parallelism, policy))
84
+ block('OG_CONFIG_REFERENCE', '/parallelism', message);
85
+ if (plan.diagnostics.length)
86
+ return plan;
87
+ parallelism = resolveParallelism(parallelism, snapshot.config.providers?.[0]);
88
+ const ceilingLayers = [parallelism.budgets?.perRun, parallelism.budgets?.perTask,
89
+ { maxAttempts: parallelism.retry?.maxAttempts ?? 3 }, snapshot.constraints?.ceilings, request.ceilings];
90
+ for (const key of ['tokens', 'costUsd', 'wallSeconds', 'maxAttempts']) {
91
+ const values = ceilingLayers.map(layer => layer?.[key]).filter((value) => value !== undefined);
92
+ if (values.some(value => !Number.isFinite(value) || value < 0 || key !== 'costUsd' && !Number.isSafeInteger(value))) {
93
+ block('OG_CONFIG_REFERENCE', `/request/ceilings/${key}`, 'Ceilings must be finite nonnegative values; counts must be integers');
94
+ }
95
+ else if (values.length)
96
+ plan.ceilings[key] = Math.min(...values);
97
+ }
98
+ if (plan.ceilings.maxAttempts === 0)
99
+ block('OG_BUDGET_UNMEASURABLE', '/request/ceilings/maxAttempts', 'No task attempts remain');
100
+ const qualifiedRoles = {};
101
+ for (const [groupId, group] of Object.entries(parallelism.groups ?? {})) {
102
+ for (const member of group.members ?? []) {
103
+ const observed = findWorkerModelRow(snapshot.catalog.discovery?.instances?.[member.cli]?.models, member.model)?.worker;
104
+ qualifiedRoles[`${groupId}/${member.id}`] = observed?.qualification.status === 'qualified'
105
+ ? observed.qualification.roles.filter(role => ownWorkerRoleGuidance(policy, role)?.groups.includes(groupId)) : [];
106
+ }
107
+ }
108
+ // Qualification gaps are group-scoped: an unqualified group must not block a
109
+ // request that never considers it. Gaps are applied once the candidates are known.
110
+ const qualificationGaps = validateWorkerGroupQualifications(parallelism, qualifiedRoles).map(diagnostic => ({
111
+ ...diagnostic, message: `${diagnostic.message}. Run aiwg doctor --probe-workers --qualify.`,
112
+ }));
113
+ const gapGroup = (diagnostic) => diagnostic.pointer.split('/')[3] ?? '';
114
+ const taskRole = request.taskClass && policy.taskClasses && Object.hasOwn(policy.taskClasses, request.taskClass) ? policy.taskClasses[request.taskClass] : undefined;
115
+ const role = request.role ?? taskRole;
116
+ plan.role = role ?? null;
117
+ if (request.taskClass && (!taskRole || request.role && taskRole !== request.role))
118
+ block('OG_CONFIG_REFERENCE', '/request/taskClass', 'Unknown task class or conflicting role');
119
+ const guidance = role ? ownWorkerRoleGuidance(policy, role) : undefined;
120
+ if (!role || !guidance)
121
+ block('OG_CONFIG_REFERENCE', '/defaults/workerSelection/roleGuidance', 'Requested role has no guidance');
122
+ if (request.member && !request.group)
123
+ block('OG_CONFIG_REFERENCE', '/request/member', 'Group-local member pins require a group');
124
+ if (request.group && !guidance?.groups.includes(request.group))
125
+ block('OG_CONFIG_REFERENCE', '/request/group', 'Group is outside role guidance');
126
+ if ([request.maxParallel, snapshot.constraints?.maxParallel].some(value => value !== undefined && (!Number.isSafeInteger(value) || value < 0)))
127
+ block('OG_CONFIG_REFERENCE', '/request/maxParallel', 'Capacity ceilings must be nonnegative integers');
128
+ if (request.requireDifferentFamily && (!request.reviewOf || validateWorkerModelObservation(request.reviewOf).length
129
+ || hasSelectionRelevantConflicts(request.reviewOf) || !request.reviewOf.family || request.reviewOf.family === 'unknown')) {
130
+ block('OG_MODEL_UNAPPROVED', '/request/reviewOf', 'Required review needs unambiguous observed source lineage');
131
+ }
132
+ const candidateGroups = request.group ? [request.group] : guidance?.groups ?? [];
133
+ const unqualifiedGroups = new Set(qualificationGaps.map(gapGroup));
134
+ const qualifiedGroups = candidateGroups.filter(groupId => !unqualifiedGroups.has(groupId));
135
+ if (!qualifiedGroups.length) {
136
+ plan.diagnostics.push(...qualificationGaps.filter(gap => candidateGroups.includes(gapGroup(gap))));
137
+ }
138
+ else {
139
+ // Unpinned requests skip an unqualified guidance group visibly instead of failing the role.
140
+ for (const groupId of candidateGroups.filter(groupId => unqualifiedGroups.has(groupId))) {
141
+ const gaps = qualificationGaps.filter(gap => gapGroup(gap) === groupId);
142
+ for (const member of parallelism.groups?.[groupId]?.members ?? []) {
143
+ plan.exclusions.push({ group: groupId, member: member.id, model: member.model, effort: null, diagnostics: gaps });
144
+ }
145
+ }
146
+ }
147
+ if (plan.diagnostics.length || !role || !guidance)
148
+ return plan;
149
+ const baseRole = guidance.baseRole ?? role;
150
+ const wrapperPin = snapshot.models.agentOverrides[MODEL_WRAPPERS[baseRole]]?.['model-override'];
151
+ const groupPolicies = new Map();
152
+ const groups = qualifiedGroups;
153
+ for (const groupId of groups) {
154
+ const group = parallelism.groups[groupId];
155
+ const narrowed = mergeGroupWorkerPolicy(policy, group);
156
+ groupPolicies.set(groupId, narrowed.policy);
157
+ if (narrowed.diagnostics.length) {
158
+ plan.diagnostics.push(...narrowed.diagnostics);
159
+ continue;
160
+ }
161
+ const groupPolicy = narrowed.policy;
162
+ const permissions = { ...group.execution, transport: group.execution?.transport ?? 'shell' };
163
+ const transport = permissions.transport;
164
+ if (request.transport === 'mcp' && permissions.launchMode === 'native-sandbox') {
165
+ const reason = diagnostic('OG_POLICY_RELAXATION', `/parallelism/groups/${groupId}/execution/launchMode`, 'MCP worker-invoke does not support native-sandbox isolation. Use models resolve --transport shell and the shell launcher, or select a group with systemd-unit isolation.');
166
+ for (const member of group.members ?? [])
167
+ plan.exclusions.push({ group: groupId, member: member.id, model: member.model, effort: null, diagnostics: [reason] });
168
+ if (request.group === groupId)
169
+ plan.diagnostics.push(reason);
170
+ continue;
171
+ }
172
+ // Priority is guidance only. Preserve declaration order for ties; fallback order stays explicit.
173
+ const members = (group.members ?? []).map((member, index) => ({ member, index })).sort((a, b) => (a.member.priority ?? 100) - (b.member.priority ?? 100) || a.index - b.index);
174
+ for (const { member } of members) {
175
+ const binding = snapshot.installations[member.cli];
176
+ const discovery = snapshot.catalog.discovery?.instances?.[member.cli];
177
+ const row = findWorkerModelRow(discovery?.models, member.model);
178
+ const observation = row?.worker;
179
+ const efforts = request.effort !== undefined ? [request.effort]
180
+ : [...new Set([guidance.initialEffort, ...guidance.effortLadder])];
181
+ for (const effort of efforts) {
182
+ const tuple = { group: groupId, member: member.id, model: member.model, effort };
183
+ const reasons = [];
184
+ const deny = (code, pointer, message) => { reasons.push(diagnostic(code, pointer, message)); };
185
+ const pointer = `/parallelism/groups/${groupId}/members/${member.id}`;
186
+ if (request.transport !== undefined && request.transport !== transport)
187
+ deny('OG_POLICY_RELAXATION', '/request/transport', 'Requested transport differs from resolved group permissions');
188
+ if (member.enabled === false || parallelism.clis?.[member.cli]?.enabled === false)
189
+ deny('OG_CONFIG_REFERENCE', pointer, 'Member or installation is disabled');
190
+ if (!member.roles.includes(baseRole))
191
+ deny('OG_CONFIG_REFERENCE', pointer, 'Member does not cover requested role');
192
+ const pinMismatch = request.member && request.member !== member.id || request.model && request.model !== member.model || wrapperPin && wrapperPin !== member.model;
193
+ const substitution = request.substitution && matchesChoice(tuple, request.substitution) && request.substitution.rationale.trim();
194
+ if (pinMismatch && !substitution)
195
+ deny('OG_PIN_MISMATCH', pointer, 'Exact request or wrapper pin requires explicit substitution');
196
+ if (!observation || !binding || !row?.llmProvider || !row.apiModelId)
197
+ deny('OG_ADAPTER_UNQUALIFIED', pointer, 'Missing exact model, inference provider, observation or current installation evidence. Run aiwg doctor --probe-workers --qualify.');
198
+ if (observation && binding && row?.llmProvider && row.apiModelId) {
199
+ const shapeErrors = validateWorkerModelObservation(observation);
200
+ if (shapeErrors.length) {
201
+ deny('OG_ADAPTER_UNQUALIFIED', '/worker', shapeErrors.join('; '));
202
+ plan.exclusions.push({ ...tuple, diagnostics: reasons });
203
+ continue;
204
+ }
205
+ if (observation.cliId !== member.cli || observation.runtimeVersion !== binding.cliVersion
206
+ || observation.accountScope !== binding.accountScope || observation.endpointFingerprint !== binding.endpointFingerprint
207
+ || discovery?.accountBinding !== binding.accountScope || discovery?.runtimeVersion !== binding.cliVersion
208
+ || parallelism.clis?.[member.cli]?.accountScope && parallelism.clis[member.cli].accountScope !== binding.accountScope) {
209
+ deny('OG_ADAPTER_UNQUALIFIED', pointer, 'Catalog and current installation scope differ');
210
+ }
211
+ if (group.efforts && (effort === null || !group.efforts.includes(effort)))
212
+ deny('OG_EFFORT_DENIED', pointer, 'Effort is outside group ceiling');
213
+ reasons.push(...validateWorkerPolicyRoute({ policy: groupPolicy, role, inferenceProvider: row.llmProvider, apiModelId: row.apiModelId,
214
+ selectedModel: member.model, effort, identityEvidence: binding.identityEvidence, observation,
215
+ wrapperPin, ...(substitution ? { substitution: request.substitution } : {}), dataClass: request.dataClass, now, context: request.context }));
216
+ if (request.requireDifferentFamily && (observation.family === 'unknown' || observation.family === request.reviewOf.family))
217
+ deny('OG_MODEL_UNAPPROVED', '/worker/family', 'Required review must use a different observed family');
218
+ try {
219
+ const { adapter } = resolveWorkerGroupInstallation(parallelism, member.cli, snapshot.registry);
220
+ const configuredProfile = parallelism.clis?.[member.cli]?.invocationProfile;
221
+ const profilePointer = `/parallelism/clis/${member.cli}/invocationProfile`;
222
+ if (configuredProfile && !Object.hasOwn(adapter.invocationProfiles ?? {}, configuredProfile)) {
223
+ deny('OG_CONFIG_REFERENCE', profilePointer, 'Configured invocation profile is not registered for this adapter; select a registered profile.');
224
+ }
225
+ else if (configuredProfile && configuredProfile !== binding.profile) {
226
+ deny('OG_PIN_MISMATCH', profilePointer, 'Configured invocation profile differs from installation qualification; qualify the selected profile again.');
227
+ }
228
+ const configuredServer = parallelism.clis?.[member.cli]?.mcpServerRef;
229
+ if (transport === 'mcp' && configuredServer && configuredServer !== binding.mcp?.serverRef)
230
+ throw new Error('Configured MCP server changed');
231
+ if (!hasOperatorWorkerNativeRenderer(adapter) && (adapter.capabilities.modelPin === 'unsupported' || !adapter.capabilities.nativeFallbackControllable))
232
+ throw new Error('Exact model or fallback control is unqualified; qualify an adapter with these controls');
233
+ if (policy.guards?.denySelfDelegation !== false && !adapter.capabilities.nestedAgentsControllable)
234
+ throw new Error('Child-agent control is unqualified. Review models.json defaults.workerSelection.guards.denySelfDelegation; false permits uncontrolled child agents without qualifying their behavior.');
235
+ if (binding.identityEvidence === 'backend-attested' && adapter.capabilities.modelPin !== 'observed')
236
+ throw new Error('Requested-only mapping cannot attest backend identity');
237
+ if (!hasOperatorWorkerNativeRenderer(adapter) && group.execution?.sandbox && !adapter.capabilities.sandboxModes.includes(group.execution.sandbox))
238
+ throw new Error('Requested sandbox mode is unqualified');
239
+ assertWorkerLaunchMode(adapter, permissions);
240
+ qualifyWorkerInvocationProfile(adapter, { profile: binding.profile, transport, cliVersion: binding.cliVersion,
241
+ policy, permissions, effort, boundary: binding.boundary,
242
+ requiredControls: request.requiredControls, mcp: binding.mcp });
243
+ if (hasOperatorWorkerNativeRenderer(adapter) && transport === 'shell' && permissions.sandbox === 'external') {
244
+ reasons.push({ code: 'OG_SANDBOX_EXTERNAL', blocking: false,
245
+ pointer: `/parallelism/groups/${groupId}/execution/sandbox`,
246
+ message: `${adapter.provider} CLI's own sandbox is disabled by explicit external policy; isolation relies on the per-task worktree and launcher resource scope.` });
247
+ }
248
+ const { maxAttempts: _maxAttempts, ...budgetLimits } = plan.ceilings;
249
+ const budgetDimensions = { tokens: 'tokens', cost: 'costUsd', 'wall-time': 'wallSeconds' };
250
+ const enforceable = adapter.capabilities.hardBudget.map(key => budgetDimensions[key]);
251
+ for (const message of validateWorkerBudgetEnforcement({ ...parallelism.budgets, perTask: budgetLimits }, enforceable))
252
+ deny('OG_BUDGET_UNMEASURABLE', '/parallelism/budgets', message);
253
+ }
254
+ catch (error) {
255
+ deny('OG_ADAPTER_UNQUALIFIED', pointer, String(error));
256
+ }
257
+ let key;
258
+ try {
259
+ key = workerModelKey(row.llmProvider, row.apiModelId);
260
+ }
261
+ catch {
262
+ plan.exclusions.push({ ...tuple, diagnostics: reasons });
263
+ continue;
264
+ }
265
+ if (snapshot.constraints?.revokedModels?.includes(key))
266
+ deny('OG_MODEL_UNAPPROVED', '/constraints/revokedModels', 'Current model revocation');
267
+ if (snapshot.constraints?.unavailableMembers?.includes(`${groupId}/${member.id}`))
268
+ deny('OG_ADAPTER_UNQUALIFIED', pointer, 'Member is currently unavailable');
269
+ const premium = ['premium', 'max-quality'].includes(guidance.tier) || observation.pricing.costClass === 'premium';
270
+ // Worker candidates always invoke a model; deterministic/routine hints must not bypass premium authority.
271
+ const authority = routeModelTier({ ...request.authority, deterministic: false, routine: false,
272
+ defaultTier: guidance.tier === 'economy' ? 1 : 2, requestedPremium: premium || request.authority?.requestedPremium });
273
+ if (authority.requiresConfirmation)
274
+ deny('OG_MODEL_UNAPPROVED', '/request/authority', `${authority.rationale.join('; ')}; agents may pass --authorize-premium only after the human explicitly confirmed the premium escalation (escalation-discipline rule)`);
275
+ const installation = parallelism.clis?.[member.cli];
276
+ const caps = [parallelism.max_parallel_subagents, group.maxParallel, parallelism.admission?.groupCaps?.[groupId],
277
+ parallelism.admission?.memberCaps?.[`${groupId}/${member.id}`], parallelism.admission?.cliCaps?.[member.cli],
278
+ parallelism.admission?.modelCaps?.[key], installation && parallelism.admission?.quotaCaps?.[installation.quotaScope],
279
+ snapshot.constraints?.maxParallel, request.maxParallel].filter((value) => value !== undefined);
280
+ const effectiveMaxParallel = caps.length ? Math.min(...caps) : null;
281
+ if (effectiveMaxParallel === 0)
282
+ deny('OG_ADAPTER_UNQUALIFIED', '/constraints/maxParallel', 'Current capacity ceiling is zero');
283
+ if (!reasons.some(reason => reason.blocking !== false))
284
+ plan.eligible.push({ ...tuple, cli: member.cli,
285
+ inferenceProvider: row.llmProvider, modelKey: key, family: observation.family, identityEvidence: binding.identityEvidence,
286
+ profile: binding.profile, transport,
287
+ permissions: structuredClone(permissions), context: workerContextHeadroom(request.context, observation),
288
+ observedAt: observation.observedAt, verifiedAt: observation.verifiedAt, observationRef: observation.recordId,
289
+ effectiveMaxParallel, diagnostics: reasons });
290
+ }
291
+ if (reasons.some(reason => reason.blocking !== false))
292
+ plan.exclusions.push({ ...tuple, diagnostics: reasons });
293
+ }
294
+ }
295
+ }
296
+ if (request.choice) {
297
+ if (!request.choice.rationale.trim())
298
+ block('OG_CONFIG_REFERENCE', '/request/choice/rationale', 'Conductor choice requires a rationale');
299
+ plan.selected = plan.eligible.find(tuple => matchesChoice(tuple, request.choice)) ?? null;
300
+ if (!plan.selected)
301
+ block('OG_MODEL_UNAPPROVED', '/request/choice', 'Conductor choice is outside the eligible set');
302
+ }
303
+ else
304
+ plan.selected = plan.eligible[0] ?? null;
305
+ if (plan.diagnostics.length)
306
+ plan.selected = null;
307
+ if (plan.selected) {
308
+ plan.policy = groupPolicies.get(plan.selected.group);
309
+ plan.status = 'eligible';
310
+ plan.diagnostics.push(...plan.selected.diagnostics.filter(item => item.code === 'OG_SANDBOX_EXTERNAL'));
311
+ plan.choice = { source: request.choice ? 'conductor' : 'default', rationale: request.choice?.rationale ?? 'Role group order, member priority/declaration order, then qualified effort ladder',
312
+ ...(request.substitution && matchesChoice(plan.selected, request.substitution) ? { substitution: structuredClone(request.substitution) } : {}) };
313
+ }
314
+ plan.alternatives = plan.eligible.filter(tuple => tuple !== plan.selected);
315
+ return plan;
316
+ }
317
+ //# sourceMappingURL=worker-plan.js.map
@@ -0,0 +1,217 @@
1
+ // Validates and merges worker selection restrictions and constrained role aliases.
2
+ import { z } from 'zod';
3
+ import { validLocalOnlyPath } from './conductor-data-policy.mjs';
4
+ import { integer } from '../schema/zod-validation.mjs';
5
+ const uniqueStrings = z.array(z.string().min(1)).refine(values => new Set(values).size === values.length, 'Duplicate entries');
6
+ const WorkerDataPolicySchema = z.strictObject({
7
+ localOnlyPaths: uniqueStrings.refine(values => values.every(validLocalOnlyPath), 'Expected literal project-relative paths').optional(),
8
+ allowedProcessing: z.array(z.enum(['local', 'remote'])).refine(values => new Set(values).size === values.length).optional(),
9
+ allowProductImprovement: z.boolean().optional(),
10
+ allowUnknown: z.boolean().optional(),
11
+ maxRetentionDays: integer().nonnegative().optional(),
12
+ });
13
+ const baseRoles = ['efficiency', 'coding', 'reasoning'];
14
+ const WorkerRoleSchema = z.strictObject({
15
+ baseRole: z.enum(baseRoles).optional(),
16
+ groups: uniqueStrings.refine(values => values.length > 0),
17
+ tier: z.enum(['economy', 'standard', 'premium', 'max-quality']),
18
+ initialEffort: z.string().min(1).nullable(),
19
+ effortLadder: uniqueStrings,
20
+ escalateAfter: integer().positive().optional(),
21
+ maxEscalations: integer().nonnegative().optional(),
22
+ deescalateAfter: integer().positive().optional(),
23
+ allowNotApplicableEffort: z.boolean().optional(),
24
+ });
25
+ const reservedRoleKey = (key) => key === 'prototype' || Object.hasOwn(Object.prototype, key);
26
+ const roleGuidanceSchema = z.preprocess((input, context) => {
27
+ if (input !== null && typeof input === 'object')
28
+ for (const role of Object.keys(input)) {
29
+ if (reservedRoleKey(role))
30
+ context.addIssue({ code: 'custom', path: [role], message: `Reserved worker role alias key: ${role}` });
31
+ }
32
+ return input;
33
+ }, z.record(z.string().regex(/^[a-z][a-z0-9-]{0,62}$/), WorkerRoleSchema));
34
+ /** Inherited object members never constitute configured role guidance. */
35
+ export function ownWorkerRoleGuidance(policy, role) {
36
+ return policy?.roleGuidance && Object.hasOwn(policy.roleGuidance, role) ? policy.roleGuidance[role] : undefined;
37
+ }
38
+ export const WorkerSelectionPolicySchema = z.strictObject({
39
+ roleGuidance: roleGuidanceSchema.optional(),
40
+ guards: z.strictObject({
41
+ deniedEfforts: uniqueStrings.optional(),
42
+ deniedModels: uniqueStrings.optional(),
43
+ denySelfDelegation: z.boolean().optional(),
44
+ requireExactModel: z.boolean().optional(),
45
+ allowedVisibility: z.array(z.enum(['listed', 'hidden'])).refine(v => new Set(v).size === v.length).optional(),
46
+ allowedLifecycle: z.array(z.enum(['active', 'deprecated'])).refine(v => new Set(v).size === v.length).optional(),
47
+ minimumIdentityEvidence: z.enum(['runtime-configured', 'backend-attested']).optional(),
48
+ }).optional(),
49
+ dataPolicy: WorkerDataPolicySchema.optional(),
50
+ dataClasses: z.record(z.string().regex(/^[a-z][a-z0-9-]{0,62}$/), WorkerDataPolicySchema).optional(),
51
+ freshness: z.strictObject({
52
+ warnHours: integer().positive().optional(),
53
+ blockHours: integer().positive().optional(),
54
+ policyDays: integer().positive().optional(),
55
+ }).optional(),
56
+ taskClasses: z.record(z.string().regex(/^[a-z][a-z0-9-]{0,62}$/), z.string().min(1)).optional(),
57
+ }).superRefine((policy, context) => {
58
+ for (const [role, guidance] of Object.entries(policy.roleGuidance ?? {})) {
59
+ if (baseRoles.includes(role) ? guidance.baseRole !== undefined : guidance.baseRole === undefined)
60
+ context.addIssue({ code: 'custom', path: ['roleGuidance', role], message: 'Unknown worker role requires a baseRole; base roles cannot be aliases' });
61
+ const base = guidance.baseRole && ownWorkerRoleGuidance(policy, guidance.baseRole);
62
+ if (base)
63
+ for (const message of aliasRestrictionErrors(guidance, base))
64
+ context.addIssue({ code: 'custom', path: ['roleGuidance', role], message });
65
+ if (guidance.effortLadder.includes('none') || (guidance.initialEffort === 'none' ? guidance.effortLadder.length !== 0 : guidance.initialEffort !== null && !guidance.effortLadder.includes(guidance.initialEffort))) {
66
+ context.addIssue({ code: 'custom', path: ['roleGuidance', role], message: 'Initial effort must belong to the ladder; real none requires an empty ladder' });
67
+ }
68
+ if (guidance.initialEffort === null && (guidance.allowNotApplicableEffort !== true || guidance.effortLadder.length !== 0)) {
69
+ context.addIssue({ code: 'custom', path: ['roleGuidance', role], message: 'Null effort requires an empty ladder and allowNotApplicableEffort=true' });
70
+ }
71
+ }
72
+ for (const key of policy.guards?.deniedModels ?? []) {
73
+ if (!isCanonicalWorkerModelKey(key))
74
+ context.addIssue({ code: 'custom', path: ['guards', 'deniedModels'], message: 'Noncanonical inference model key' });
75
+ }
76
+ if (policy.freshness?.warnHours !== undefined && policy.freshness.blockHours !== undefined && policy.freshness.warnHours > policy.freshness.blockHours) {
77
+ context.addIssue({ code: 'custom', path: ['freshness'], message: 'warnHours must not exceed blockHours' });
78
+ }
79
+ for (const role of Object.values(policy.taskClasses ?? {})) {
80
+ if (!baseRoles.includes(role) && !ownWorkerRoleGuidance(policy, role)?.baseRole)
81
+ context.addIssue({ code: 'custom', path: ['taskClasses'], message: 'Unknown worker role' });
82
+ }
83
+ });
84
+ /** Aliases may reorder/subset choices, never change base authority or escalation controls. */
85
+ function aliasRestrictionErrors(alias, base) {
86
+ const errors = [];
87
+ if (alias.groups.some(group => !base.groups.includes(group)))
88
+ errors.push('Alias groups widen base role');
89
+ if (alias.effortLadder.some(effort => !base.effortLadder.includes(effort))
90
+ || alias.initialEffort === 'none' && base.initialEffort !== 'none'
91
+ || alias.initialEffort === null && base.initialEffort !== null
92
+ || alias.allowNotApplicableEffort === true && base.allowNotApplicableEffort !== true)
93
+ errors.push('Alias effort choices widen base role');
94
+ if (alias.tier !== base.tier)
95
+ errors.push('Alias tier must retain base role authority');
96
+ if ((alias.maxEscalations ?? base.maxEscalations ?? 2) > (base.maxEscalations ?? 2))
97
+ errors.push('Alias maxEscalations widens base role');
98
+ for (const key of ['escalateAfter', 'deescalateAfter']) {
99
+ if (alias[key] !== undefined && alias[key] !== (base[key] ?? 2))
100
+ errors.push(`Alias ${key} must retain base role control`);
101
+ }
102
+ return errors;
103
+ }
104
+ /** Canonical RFC3986 identity; installation and account never enter the key. */
105
+ export function workerModelKey(inferenceProvider, apiModelId) {
106
+ if (!/^[a-z][a-z0-9-]{0,62}$/.test(inferenceProvider) || !apiModelId)
107
+ throw new Error('OG_CONFIG_REFERENCE: invalid inference model identity');
108
+ return `${inferenceProvider}/${encodeURIComponent(apiModelId).replace(/[!'()*]/g, c => `%${c.charCodeAt(0).toString(16).toUpperCase()}`)}`;
109
+ }
110
+ export function isCanonicalWorkerModelKey(key) {
111
+ const slash = key.indexOf('/');
112
+ try {
113
+ return slash > 0 && workerModelKey(key.slice(0, slash), decodeURIComponent(key.slice(slash + 1))) === key;
114
+ }
115
+ catch {
116
+ return false;
117
+ }
118
+ }
119
+ export const DEFAULT_WORKER_SELECTION = {
120
+ guards: { deniedEfforts: ['ultra'], deniedModels: [], denySelfDelegation: true, requireExactModel: true, allowedVisibility: ['listed'], allowedLifecycle: ['active'], minimumIdentityEvidence: 'runtime-configured' },
121
+ dataPolicy: { allowedProcessing: ['local', 'remote'], allowProductImprovement: false, allowUnknown: false },
122
+ freshness: { warnHours: 24, blockHours: 168, policyDays: 30 },
123
+ taskClasses: { inventory: 'efficiency', implementation: 'coding', architecture: 'reasoning', review: 'reasoning' },
124
+ };
125
+ /** Merge leaves, preserving pre-merge explicit origins and attempted relaxations. */
126
+ export function mergeWorkerSelection(layers) {
127
+ const policy = Object.create(null);
128
+ const origins = Object.create(null);
129
+ const diagnostics = [];
130
+ const visit = (target, input, parts, layer) => {
131
+ for (const [key, value] of Object.entries(input)) {
132
+ const path = [...parts, key];
133
+ const pointer = `/defaults/workerSelection/${path.map(p => p.replace(/~/g, '~0').replace(/\//g, '~1')).join('/')}`;
134
+ if (value !== null && typeof value === 'object' && !Array.isArray(value)) {
135
+ if (!Object.hasOwn(target, key))
136
+ target[key] = Object.create(null);
137
+ visit(target[key], value, path, layer);
138
+ continue;
139
+ }
140
+ const origin = { source: layer.source, authority: layer.authority, digest: layer.digest, pointer, contribution: structuredClone(value) };
141
+ const prior = origins[pointer] ?? [];
142
+ const explicit = prior.filter(o => o.authority !== 'builtin');
143
+ let effective = structuredClone(value);
144
+ let relaxation = false;
145
+ if (layer.authority !== 'builtin' && explicit.length > 0) {
146
+ const previous = target[key];
147
+ if (['deniedEfforts', 'deniedModels', 'localOnlyPaths'].includes(key))
148
+ effective = [...new Set([...previous, ...value])];
149
+ else if (['allowedVisibility', 'allowedLifecycle', 'allowedProcessing'].includes(key)) {
150
+ relaxation = value.some((v) => !previous.includes(v));
151
+ effective = previous.filter((v) => value.includes(v));
152
+ }
153
+ else if (['denySelfDelegation', 'requireExactModel'].includes(key)) {
154
+ relaxation = previous === true && value === false;
155
+ effective = previous || value;
156
+ }
157
+ else if (['allowUnknown', 'allowProductImprovement'].includes(key)) {
158
+ relaxation = previous === false && value === true;
159
+ effective = previous && value;
160
+ }
161
+ else if (['maxRetentionDays', 'warnHours', 'blockHours', 'policyDays'].includes(key)) {
162
+ relaxation = value > previous;
163
+ effective = Math.min(previous, value);
164
+ }
165
+ else if (key === 'minimumIdentityEvidence') {
166
+ relaxation = previous === 'backend-attested' && value !== previous;
167
+ effective = previous === 'backend-attested' ? previous : value;
168
+ }
169
+ }
170
+ if (relaxation)
171
+ diagnostics.push({ code: 'OG_POLICY_RELAXATION', pointer, message: 'Explicit restriction cannot relax an inherited restriction', origins: [...explicit, origin] });
172
+ target[key] = effective;
173
+ origins[pointer] = [...prior, origin];
174
+ }
175
+ };
176
+ for (const layer of layers)
177
+ if (layer.policy) {
178
+ for (const [role, guidance] of Object.entries(layer.policy.roleGuidance ?? {})) {
179
+ if (!guidance.baseRole)
180
+ continue;
181
+ const previous = ownWorkerRoleGuidance(policy, role);
182
+ if (layer.authority !== 'project' || previous?.baseRole && previous.baseRole !== guidance.baseRole)
183
+ diagnostics.push({
184
+ code: 'OG_POLICY_RELAXATION', pointer: `/defaults/workerSelection/roleGuidance/${role}/baseRole`,
185
+ message: 'Only project layers may declare constrained aliases; inherited aliases cannot change baseRole',
186
+ });
187
+ }
188
+ visit(policy, layer.policy, [], layer);
189
+ }
190
+ for (const [role, guidance] of Object.entries(policy.roleGuidance ?? {})) {
191
+ const base = guidance.baseRole && ownWorkerRoleGuidance(policy, guidance.baseRole);
192
+ if (base)
193
+ for (const field of ['maxEscalations', 'escalateAfter', 'deescalateAfter'])
194
+ guidance[field] ??= base[field];
195
+ if (guidance.baseRole && !base)
196
+ diagnostics.push({
197
+ code: 'OG_CONFIG_REFERENCE', pointer: `/defaults/workerSelection/roleGuidance/${role}/baseRole`, message: 'Alias base role has no guidance',
198
+ });
199
+ }
200
+ const validation = WorkerSelectionPolicySchema.safeParse(policy);
201
+ if (!validation.success)
202
+ for (const issue of validation.error.issues)
203
+ diagnostics.push({ code: 'OG_CONFIG_REFERENCE', pointer: `/defaults/workerSelection/${issue.path.join('/')}`, message: issue.message });
204
+ // Data classes are applied as further restrictions to the base path.
205
+ for (const dataClass of Object.values(policy.dataClasses ?? {})) {
206
+ const base = policy.dataPolicy ?? {};
207
+ if (dataClass.allowedProcessing)
208
+ dataClass.allowedProcessing = dataClass.allowedProcessing.filter(p => !base.allowedProcessing || base.allowedProcessing.includes(p));
209
+ for (const key of ['allowUnknown', 'allowProductImprovement'])
210
+ if (base[key] === false)
211
+ dataClass[key] = false;
212
+ if (base.maxRetentionDays !== undefined)
213
+ dataClass.maxRetentionDays = Math.min(dataClass.maxRetentionDays ?? base.maxRetentionDays, base.maxRetentionDays);
214
+ }
215
+ return { policy, origins, diagnostics };
216
+ }
217
+ //# sourceMappingURL=worker-selection-policy.js.map
@@ -156,7 +156,7 @@ export async function verifyModelWrapperDeployment(agentsPath, expectation = {})
156
156
  const missing = [];
157
157
  const mismatches = [];
158
158
  for (const [role, wrapper] of expected) {
159
- const matches = files.filter(file => path.basename(file).replace(/\.(?:md|toml|json|yaml|yml)$/i, '') === wrapper);
159
+ const matches = files.filter(file => path.basename(file).replace(/(?:\.agent)?\.(?:md|toml|json|yaml|yml)$/i, '') === wrapper);
160
160
  if (matches.length === 0) {
161
161
  missing.push(wrapper);
162
162
  continue;