@aiwg/cli 2026.11.0 → 2026.11.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (89) hide show
  1. package/agentic/code/providers/flue/README.md +2 -1
  2. package/dist/src/artifacts/cli.js +3 -2
  3. package/dist/src/artifacts/discover-facets.js +2 -0
  4. package/dist/src/artifacts/discover-session-facets.js +14 -0
  5. package/dist/src/artifacts/fortemi-core-query-adapter.js +4 -4
  6. package/dist/src/artifacts/framework-capabilities.js +7 -3
  7. package/dist/src/artifacts/index-builder.js +2 -3
  8. package/dist/src/artifacts/query-engine-discover-output.js +3 -3
  9. package/dist/src/artifacts/query-engine-discover.js +61 -14
  10. package/dist/src/artifacts/query-engine-entries.js +52 -9
  11. package/dist/src/artifacts/query-engine-installation.js +27 -0
  12. package/dist/src/artifacts/query-engine-rules.js +1 -2
  13. package/dist/src/artifacts/query-engine-scoring.js +33 -31
  14. package/dist/src/artifacts/query-engine-show-card.js +6 -2
  15. package/dist/src/artifacts/query-engine-show.js +2 -2
  16. package/dist/src/artifacts/relations.js +17 -10
  17. package/dist/src/cli/handlers/checkpoint.js +143 -0
  18. package/dist/src/cli/handlers/help.js +1 -0
  19. package/dist/src/cli/handlers/index.js +4 -2
  20. package/dist/src/cli/handlers/models-resource-sample.js +7 -3
  21. package/dist/src/cli/handlers/ralph-launcher.js +1 -1
  22. package/dist/src/cli/handlers/script-runner.js +2 -1
  23. package/dist/src/cli/handlers/steward-signing.js +44 -0
  24. package/dist/src/cli/handlers/steward.js +5 -0
  25. package/dist/src/cli/handlers/use-provider-results.js +17 -0
  26. package/dist/src/cli/handlers/use.js +9 -15
  27. package/dist/src/cli/router.js +12 -2
  28. package/dist/src/cli/user-scope-mirror.js +3 -1
  29. package/dist/src/config/aiwg-config.js +5 -1
  30. package/dist/src/config/cli.js +1 -0
  31. package/dist/src/config/delivery-validation.js +21 -0
  32. package/dist/src/config/host-resource-report.d.mts +1 -1
  33. package/dist/src/config/host-resource-report.mjs +23 -4
  34. package/dist/src/config/host-resource-runtime.d.mts +8 -0
  35. package/dist/src/config/host-resource-runtime.mjs +67 -24
  36. package/dist/src/config/index-graph-overrides.js +4 -0
  37. package/dist/src/config/worker-attribution.d.mts +7 -0
  38. package/dist/src/config/worker-attribution.mjs +44 -0
  39. package/dist/src/delivery/git.js +62 -0
  40. package/dist/src/delivery/pr.js +149 -0
  41. package/dist/src/delivery/tracker.js +33 -0
  42. package/dist/src/discovery/interview.js +1 -1
  43. package/dist/src/extensions/claude-hooks-installer.js +1 -0
  44. package/dist/src/extensions/loader.js +2 -1
  45. package/dist/src/issues/cli.js +12 -3
  46. package/dist/src/issues/external-cli.js +76 -0
  47. package/dist/src/issues/live.js +18 -1
  48. package/dist/src/issues/tracker-policy.js +17 -0
  49. package/dist/src/mcp/tools/worker-invoke.mjs +2 -1
  50. package/dist/src/mcp/tools/worker-stdin-runtime.mjs +12 -0
  51. package/dist/src/models/conductor-data-policy.d.mts +3 -2
  52. package/dist/src/models/conductor-data-policy.mjs +94 -5
  53. package/dist/src/models/worker-plan.js +3 -3
  54. package/dist/src/models/worker-selection-policy.js +2 -1
  55. package/dist/src/providers/deployment-lock.js +77 -0
  56. package/dist/src/providers/deployment-ownership.d.mts +12 -2
  57. package/dist/src/providers/deployment-ownership.mjs +115 -21
  58. package/dist/src/providers/deployment-preservation.d.mts +2 -1
  59. package/dist/src/providers/deployment-preservation.mjs +3 -0
  60. package/dist/src/providers/provider-definitions.js +4 -0
  61. package/dist/src/serve/worker-invocation-preparation.js +3 -1
  62. package/dist/src/serve/worker-invocation.js +2 -0
  63. package/dist/src/skills/run.js +5 -0
  64. package/dist/src/smiths/hook-bridge/codex-translator.js +3 -1
  65. package/dist/src/smiths/hook-bridge/hermes-translator.js +3 -1
  66. package/dist/src/smiths/hook-bridge/prompt-discovery-gaps.js +6 -0
  67. package/package.json +4 -2
  68. package/schemas/models/model-config-compatibility.v1.schema.json +4 -0
  69. package/tools/agents/deploy-agents.mjs +15 -0
  70. package/tools/agents/providers/base-contract.mjs +7 -1
  71. package/tools/agents/providers/base-inventory.mjs +35 -13
  72. package/tools/agents/providers/base.mjs +1 -1
  73. package/tools/agents/providers/conductor-data-guard.mjs +35 -11
  74. package/tools/agents/providers/muse-hooks.mjs +4 -0
  75. package/tools/agents/providers/muse-prompt-discovery.mjs +22 -0
  76. package/tools/agents/providers/provider-prepare-coordinator.mjs +15 -10
  77. package/tools/agents/providers/rule-delivery-surface.mjs +6 -3
  78. package/tools/agents/providers/rule-deployment-commit.mjs +10 -0
  79. package/tools/agents/providers/stale-artifact-prune.mjs +9 -8
  80. package/tools/ralph-external/lib/worker-capture.mjs +157 -0
  81. package/tools/ralph-external/lib/worker-health.mjs +3 -0
  82. package/tools/ralph-external/lib/worker-invocation-processes.mjs +9 -6
  83. package/tools/ralph-external/lib/worker-launch-cli.mjs +10 -1
  84. package/tools/ralph-external/lib/worker-process-identity.mjs +30 -0
  85. package/tools/ralph-external/lib/worker-retry-evidence.mjs +87 -6
  86. package/tools/ralph-external/lib/worker-termination.mjs +56 -6
  87. package/tools/ralph-external/process-monitor.mjs +12 -18
  88. package/tools/ralph-external/session-launcher.mjs +43 -29
  89. package/vscode-extension/schemas/aiwg.config.v1.json +15 -0
@@ -31,7 +31,8 @@ export function hostResourceReport({ config, live, readers, paths, thresholdOver
31
31
  throw new Error(`Unknown group "${group}"; configured groups: ${Object.keys(configured).join(', ') || '(none)'}`);
32
32
  }
33
33
  // Local collection and evaluation share one clock; supplied snapshots retain their source time.
34
- const measured = live ?? readLiveHostResources({ ...readers, now, paths, groupNames: Object.keys(configured) });
34
+ const measured = live ?? readLiveHostResources({ ...readers, now, paths, workspace: readers?.workspace ?? paths?.[0],
35
+ groupNames: Object.keys(configured) });
35
36
  const evaluated = now();
36
37
  const origins = {};
37
38
  let thresholds;
@@ -72,8 +73,13 @@ export function hostResourceReport({ config, live, readers, paths, thresholdOver
72
73
  'less than one core of load headroom');
73
74
  if (thresholds.max_workers !== undefined) add('max_workers', thresholds.max_workers - measured.workers,
74
75
  'running workers exhaust the host ceiling or cannot be counted');
76
+ // The project ceiling counts this workspace's attributed workers plus unattributed ones;
77
+ // workers attributed to another workspace consume host capacity (max_workers) only.
78
+ const attributed = Object.values(measured.workerGroups ?? {}).reduce((sum, count) => sum + count, 0);
79
+ const projectRunning = Number.isFinite(measured.workers) && measured.workerGroups && Number.isFinite(measured.workerUnknown)
80
+ ? Math.min(measured.workers, attributed + measured.workerUnknown) : measured.workers;
75
81
  const admission = [
76
- { threshold: 'max_parallel_subagents', limit: parallelism?.max_parallel_subagents
82
+ { threshold: 'max_parallel_subagents', running: projectRunning, limit: parallelism?.max_parallel_subagents
77
83
  ?? (parallelism?.worker_dispatch ? getProviderParallelismDefaults(config?.providers?.[0]).max_parallel_subagents : undefined) },
78
84
  ...(caps ?? []),
79
85
  ];
@@ -82,8 +88,9 @@ export function hostResourceReport({ config, live, readers, paths, thresholdOver
82
88
  if (limit !== undefined && limit !== null) add(threshold, limit - running,
83
89
  'admission capacity exhausted or worker count unavailable');
84
90
  }
91
+ const unknown = measured.workerUnknown
92
+ ?? measured.workers - Object.values(measured.workerGroups ?? {}).reduce((sum, count) => sum + count, 0);
85
93
  const groups = Object.entries(configured).map(([id, settings]) => {
86
- const unknown = measured.workers - Object.values(measured.workerGroups ?? {}).reduce((sum, count) => sum + count, 0);
87
94
  const running = (measured.workerGroups?.[id] ?? 0) + unknown;
88
95
  const candidates = [
89
96
  { threshold: `groups.${id}.maxParallel`, limit: settings.maxParallel },
@@ -101,10 +108,22 @@ export function hostResourceReport({ config, live, readers, paths, thresholdOver
101
108
  return { group: id, maxParallel: settings.maxParallel ?? null, slots,
102
109
  reason: threshold ? `${threshold}: ${reason}` : reason };
103
110
  });
111
+ // Capacity diagnostics retain inspectable census identities without environment contents.
112
+ const blockers = measured.workerAttributions ?? [];
113
+ for (const failure of failures) {
114
+ if (/workers|max_parallel|admission|groups\./.test(failure.signal)) {
115
+ failure.code = unknown > 0 && !failure.signal.endsWith('.enabled')
116
+ ? 'OG_HOST_ATTRIBUTION' : 'OG_HOST_CAPACITY';
117
+ if (!blockers.length) continue;
118
+ failure.reason += `; host workers=${measured.workers ?? 'unavailable'}, unattributed=${unknown ?? 'unavailable'}; counted: `
119
+ + (blockers.map(record => `${record.kind}:${record.id} (${record.attribution}${record.workspace ? `, ${record.workspace}/${record.group}` : ''})`).join(', ') || 'identities unavailable');
120
+ if (failure.code === 'OG_HOST_ATTRIBUTION') failure.reason += '; recovery: aiwg doctor --resources --json; see docs/getting-started/worker-attribution.md (relaunch through marked launch paths; never relabel another owner\'s jobs)';
121
+ }
122
+ }
104
123
  const slots = failures.length ? 0 : Math.min(...limits.map(limit => limit.slots));
105
124
  const limitingThreshold = failures[0]?.signal ?? [...limits].sort((a, b) => a.slots - b.slots)[0]?.threshold;
106
125
  return { measured, freshness: snapshot, thresholds, origins, slots, ok: slots > 0, limits, failures, groups, limitingThreshold,
107
126
  counting: 'current UID AIWG worker units plus distinct AIWG_WORKER_INVOCATION_ID markers outside those units; '
108
127
  + (measured.workerCountingSource === 'owned-process-fallback' ? 'systemd unavailable: owned-process fallback; ' : '')
109
- + 'hostCliProcesses: exact codex/muse/muse-bin comm, informational, not used for admission; group attribution uses unambiguous configured prefixes in existing invocation markers or unit names; unattributed workers count against every group; tuple caps without attribution use owned worker total' };
128
+ + 'hostCliProcesses: exact codex/muse/muse-bin comm, informational, not used for admission; group attribution uses workspace/group markers or unambiguous configured prefixes in existing invocation markers or unit names; unattributed workers count against every group and host capacity; tuple caps without attribution use owned worker total' };
110
129
  }
@@ -1,13 +1,19 @@
1
+ export interface WorkerAttribution {
2
+ kind: 'unit' | 'unit-count' | 'invocation'; id: string; count: number;
3
+ attribution: 'attributed' | 'unknown' | 'conflicting'; workspace?: string; group?: string;
4
+ }
1
5
  export interface HostResourceSample {
2
6
  /** Start of collection on the source host; absent on legacy/unavailable snapshots. */
3
7
  collectedAt?: string;
4
8
  supported: boolean; reason?: string; availMemGb?: number; load1?: number; cores?: number;
5
9
  loadRatio?: number; memPsiAvg10?: number; memPsiAvg60?: number; memPsiAvg300?: number;
10
+ workerAttributions?: WorkerAttribution[]; workerWorkspace?: string; workerUnknown?: number;
6
11
  workerGroups?: Record<string, number>;
7
12
  workers?: number; hostCliProcesses?: Record<string, number>; workerUnits?: number; freeDiskGb?: number;
8
13
  workerCountingSource?: 'systemd-units-and-marked-processes' | 'owned-process-fallback';
9
14
  }
10
15
  export interface WorkerCensus {
16
+ attributions?: WorkerAttribution[]; workspace?: string; unknown?: number;
11
17
  byGroup?: Record<string, number>;
12
18
  total: number; hostCliProcesses?: Record<string, number>; units?: number;
13
19
  source?: HostResourceSample['workerCountingSource'];
@@ -18,6 +24,7 @@ export interface HostResourceReaders {
18
24
  readDir?: (path: string) => string[];
19
25
  uid?: number;
20
26
  groupNames?: string[];
27
+ workspace?: string;
21
28
  coreCount?: () => number;
22
29
  countWorkers?: () => number | undefined | WorkerCensus;
23
30
  countWorkerUnits?: () => number | undefined;
@@ -27,6 +34,7 @@ export interface HostResourceReaders {
27
34
  paths?: string[];
28
35
  }
29
36
  export function readLiveHostResources(readers?: HostResourceReaders): HostResourceSample;
37
+ export function nearestDispatchPathSync(filename: string, fsOps?: { lstat?: (path: string) => { isDirectory(): boolean }; access?: (path: string, mode: number) => void }): string;
30
38
  export function countWorkerProcesses(readers?: HostResourceReaders): WorkerCensus | undefined;
31
39
  export function defaultCountWorkers(readers?: HostResourceReaders): number | undefined;
32
40
  export function countWorkerUnits(options?: { spawn?: (...args: any[]) => any }): number | undefined;
@@ -1,8 +1,9 @@
1
1
  // Linux host measurements shared by dispatch preflight and resource reports.
2
- import { readFileSync, readdirSync, statfsSync } from 'node:fs';
2
+ import { accessSync, constants as fsConstants, lstatSync, readFileSync, readdirSync, statfsSync } from 'node:fs';
3
3
  import os from 'node:os';
4
+ import { dirname } from 'node:path';
4
5
  import { spawnSync } from 'node:child_process';
5
- import { WORKER_INVOCATION_MARKER } from './worker-invocation-marker.mjs';
6
+ import { readWorkerAttribution, workerWorkspace } from './worker-attribution.mjs';
6
7
  const BYTES_PER_GB = 1024 ** 3;
7
8
 
8
9
  /**
@@ -73,6 +74,7 @@ function countWorkerProcesses({
73
74
  readDir = readdirSync,
74
75
  readText = path => readFileSync(path, 'utf8'),
75
76
  uid = process.getuid?.(),
77
+ workspace,
76
78
  groupNames = [],
77
79
  listWorkerUnits: readUnitList,
78
80
  countWorkerUnits: readUnitCount,
@@ -86,8 +88,10 @@ function countWorkerProcesses({
86
88
  if (Number.isInteger(counted) && counted >= 0) units = counted;
87
89
  } catch { /* Owned-process scanning remains available. */ }
88
90
  const source = units === undefined ? 'owned-process-fallback' : 'systemd-units-and-marked-processes';
89
- // Reuse existing identities; UUID-only IDs carry no group evidence.
91
+ const currentWorkspace = workerWorkspace(workspace);
92
+ // Keep legacy unambiguous group names; explicit markers add workspace ownership.
90
93
  const identify = value => new Set(groupNames.filter(name => value === name || value.startsWith(`${name}-`)));
94
+ const unitEvidence = new Map([...(unitNames ?? [])].map(unit => [unit, new Set()]));
91
95
  const unitGroups = new Map([...(unitNames ?? [])].map(unit =>
92
96
  [unit, identify(unit.slice('aiwg-worker-'.length, -'.service'.length))]));
93
97
  let entries, procUnavailable = false;
@@ -97,9 +101,7 @@ function countWorkerProcesses({
97
101
  entries = []; procUnavailable = true;
98
102
  }
99
103
  const hostCliProcesses = { codex: 0, muse: 0 };
100
- const invocations = new Set(), unitInvocations = new Set();
101
- const invocationGroups = new Map();
102
- const merge = (target, evidence) => { for (const name of evidence) target.add(name); };
104
+ const invocations = new Map();
103
105
  for (const entry of entries) {
104
106
  if (!/^\d+$/.test(entry)) continue;
105
107
  try {
@@ -112,27 +114,42 @@ function countWorkerProcesses({
112
114
  const comm = optional('comm').trim();
113
115
  if (comm === 'codex') hostCliProcesses.codex += 1;
114
116
  if (comm === 'muse-bin' || comm === 'muse') hostCliProcesses.muse += 1;
115
- const marker = optional('environ').split('\0').find(field => field.startsWith(`${WORKER_INVOCATION_MARKER}=`));
116
- const invocation = marker?.slice(WORKER_INVOCATION_MARKER.length + 1);
117
- if (!invocation) continue;
118
- invocations.add(invocation);
119
- if (!invocationGroups.has(invocation)) invocationGroups.set(invocation, identify(invocation));
117
+ const evidence = readWorkerAttribution(optional('environ'));
118
+ if (!evidence.invocation) continue;
119
+ if (!invocations.has(evidence.invocation)) invocations.set(evidence.invocation,
120
+ { evidence: new Set(), groups: identify(evidence.invocation), units: new Set() });
121
+ const record = invocations.get(evidence.invocation);
122
+ if (evidence.workspace && evidence.group) record.evidence.add(JSON.stringify([evidence.workspace, evidence.group]));
120
123
  const cgroupUnits = optional('cgroup').match(/aiwg-worker-[^/\s]+\.service(?=\/|\s|$)/g) ?? [];
121
- if (cgroupUnits.some(unit => unitNames ? unitNames.has(unit) : units > 0)) unitInvocations.add(invocation);
122
- for (const unit of cgroupUnits.filter(unit => unitGroups.has(unit))) {
123
- merge(unitGroups.get(unit), invocationGroups.get(invocation));
124
- }
124
+ for (const unit of cgroupUnits.filter(unit => unitNames ? unitNames.has(unit) : units > 0)) record.units.add(unit);
125
125
  } catch { /* Processes may exit during the scan. */ }
126
126
  }
127
- const byGroup = {};
128
- for (const evidence of [...unitGroups.values(), ...[...invocationGroups]
129
- .filter(([id]) => !unitInvocations.has(id)).map(([, evidence]) => evidence)]) {
130
- if (evidence.size === 1) {
131
- const [name] = evidence;
132
- byGroup[name] = (byGroup[name] ?? 0) + 1;
127
+ for (const record of invocations.values()) {
128
+ for (const unit of record.units) {
129
+ if (unitEvidence.has(unit)) for (const evidence of record.evidence) unitEvidence.get(unit).add(evidence);
130
+ if (unitGroups.has(unit)) for (const name of record.groups) unitGroups.get(unit).add(name);
133
131
  }
134
132
  }
135
- return { ...(groupNames.length ? { byGroup } : {}), total: (units ?? 0) + [...invocations].filter(id => !unitInvocations.has(id)).length,
133
+ const attributions = [];
134
+ const byGroup = {};
135
+ let unknown = 0;
136
+ const add = (kind, id, evidence, legacyGroups = new Set(), count = 1) => {
137
+ const identity = evidence.size === 1 ? JSON.parse([...evidence][0])
138
+ : !evidence.size && legacyGroups.size === 1 ? [null, [...legacyGroups][0]] : undefined;
139
+ const record = { kind, id, count, attribution: identity ? 'attributed' : evidence.size ? 'conflicting' : 'unknown',
140
+ ...(identity ? { ...(identity[0] ? { workspace: identity[0] } : {}), group: identity[1] } : {}) };
141
+ attributions.push(record);
142
+ if (!identity || (identity[0] && !currentWorkspace)) unknown += count;
143
+ if (identity && (!identity[0] || identity[0] === currentWorkspace)) {
144
+ byGroup[identity[1]] = (byGroup[identity[1]] ?? 0) + count;
145
+ }
146
+ };
147
+ for (const [unit, evidence] of unitEvidence) add('unit', unit, evidence, unitGroups.get(unit));
148
+ if (units > 0 && !unitNames) add('unit-count', '(unit identities unavailable)', new Set(), new Set(), units);
149
+ for (const [id, record] of invocations) if (!record.units.size) add('invocation', id, record.evidence, record.groups);
150
+ return { byGroup, attributions, workspace: currentWorkspace,
151
+ unknown,
152
+ total: (units ?? 0) + [...invocations.values()].filter(record => !record.units.size).length,
136
153
  ...(procUnavailable ? {} : { hostCliProcesses }), units, source };
137
154
  }
138
155
 
@@ -157,6 +174,31 @@ function toFreeDiskGb(disk) {
157
174
  return Number.isFinite(gb) && gb >= 0 ? gb : undefined;
158
175
  }
159
176
 
177
+ /**
178
+ * Pick the path to sample for a worker directory that may not exist yet,
179
+ * such as a final-output folder the launch creates (#3856). Mirrors the
180
+ * launcher's own rule (session-launcher.mjs workerDispatchPath): walk up only
181
+ * past missing entries to the nearest readable, searchable directory, and
182
+ * never settle on `/`. Anything else returns the original path so sampling
183
+ * still fails closed. Nothing is created.
184
+ */
185
+ function nearestDispatchPathSync(filename, fsOps = {}) {
186
+ const lstat = fsOps.lstat ?? lstatSync;
187
+ const access = fsOps.access ?? accessSync;
188
+ let candidate = filename;
189
+ while (dirname(candidate) !== candidate) {
190
+ try {
191
+ if (!lstat(candidate).isDirectory()) return filename;
192
+ access(candidate, fsConstants.R_OK | fsConstants.X_OK);
193
+ return candidate;
194
+ } catch (error) {
195
+ if (error?.code !== 'ENOENT') return filename;
196
+ candidate = dirname(candidate);
197
+ }
198
+ }
199
+ return filename;
200
+ }
201
+
160
202
  /**
161
203
  * Sample free disk on the caller-supplied filesystem(s): `readers.paths`
162
204
  * names the actual evidence root and worktree, and the gate takes the
@@ -235,7 +277,8 @@ function readLiveHostResources(readers = {}) {
235
277
  memPsiAvg300: psi?.avg300,
236
278
  workers: typeof workers === 'object' ? workers?.total : workers,
237
279
  ...(typeof workers === 'object' ? { hostCliProcesses: workers?.hostCliProcesses, workerUnits: workers?.units,
238
- workerCountingSource: workers?.source, workerGroups: workers?.byGroup } : {}),
280
+ workerCountingSource: workers?.source, workerGroups: workers?.byGroup, workerAttributions: workers?.attributions,
281
+ workerWorkspace: workers?.workspace, workerUnknown: workers?.unknown } : {}),
239
282
  freeDiskGb: sampleFreeDiskGb(readers),
240
283
  };
241
284
  }
@@ -293,4 +336,4 @@ function evaluateDispatchGate(live, thresholds) {
293
336
  }
294
337
 
295
338
 
296
- export { parseMemAvailableGb, parseMemoryPsi, parseLoadAverages, listWorkerUnits, countWorkerUnits, countWorkerProcesses, defaultCountWorkers, readLiveHostResources, evaluateDispatchGate };
339
+ export { parseMemAvailableGb, parseMemoryPsi, parseLoadAverages, listWorkerUnits, countWorkerUnits, countWorkerProcesses, defaultCountWorkers, readLiveHostResources, evaluateDispatchGate, nearestDispatchPathSync };
@@ -33,4 +33,8 @@ export function validateIndexGraphOverrides(overrides) {
33
33
  }
34
34
  return errors;
35
35
  }
36
+ /** Normalize graph filename patterns without loading artifact builders. */
37
+ export function normalizeNamedCaptures(pattern) {
38
+ return pattern.replace(/\(\?P</g, '(?<');
39
+ }
36
40
  //# sourceMappingURL=index-graph-overrides.js.map
@@ -0,0 +1,7 @@
1
+ import type { WorkerResolvedInvocation } from '../mission-protocol/types.js';
2
+ export const WORKER_WORKSPACE_MARKER: 'AIWG_WORKER_WORKSPACE';
3
+ export const WORKER_GROUP_MARKER: 'AIWG_WORKER_GROUP';
4
+ export function workerWorkspace(value?: string): string | undefined;
5
+ export function workerAttributionEnvironment(invocationId: string, workspace: string, group: string): Record<string, string>;
6
+ export function directWorkerEnvironment(invocation: WorkerResolvedInvocation): Record<string, string>;
7
+ export function readWorkerAttribution(environment: string): { invocation?: string; workspace?: string; group?: string };
@@ -0,0 +1,44 @@
1
+ // Workspace/group environment protocol shared by worker launchers and the host census.
2
+ import path from 'node:path';
3
+ import { realpathSync } from 'node:fs';
4
+ import { createHash } from 'node:crypto';
5
+ import { WORKER_INVOCATION_MARKER } from './worker-invocation-marker.mjs';
6
+
7
+ export const WORKER_WORKSPACE_MARKER = 'AIWG_WORKER_WORKSPACE';
8
+ export const WORKER_GROUP_MARKER = 'AIWG_WORKER_GROUP';
9
+
10
+ export function workerWorkspace(value) {
11
+ if (typeof value !== 'string' || !path.isAbsolute(value) || value.includes('\0')) return undefined;
12
+ try { return realpathSync(value); } catch { return path.normalize(value); }
13
+ }
14
+
15
+ export function workerAttributionEnvironment(invocationId, workspace, group) {
16
+ const canonical = workerWorkspace(workspace);
17
+ if (typeof invocationId !== 'string' || !invocationId || /[\0\r\n]/.test(invocationId)) {
18
+ throw new Error('Worker attribution requires a non-empty invocation ID');
19
+ }
20
+ if (!canonical || typeof group !== 'string' || !group || /[\0\r\n]/.test(group)) {
21
+ throw new Error('Worker attribution requires an absolute workspace and a non-empty group');
22
+ }
23
+ return { [WORKER_INVOCATION_MARKER]: invocationId,
24
+ [WORKER_WORKSPACE_MARKER]: canonical, [WORKER_GROUP_MARKER]: group };
25
+ }
26
+
27
+ export function directWorkerEnvironment(invocation) {
28
+ const id = invocation.invocationId ?? createHash('sha256').update(JSON.stringify([
29
+ invocation.cwd, invocation.selected, invocation.finalPath, invocation.briefDigest,
30
+ ])).digest('hex');
31
+ return workerAttributionEnvironment(id, invocation.cwd, invocation.selected.group);
32
+ }
33
+
34
+ export function readWorkerAttribution(environment) {
35
+ const fields = environment.split('\0');
36
+ const read = name => {
37
+ const values = fields.filter(field => field.startsWith(`${name}=`)).map(field => field.slice(name.length + 1));
38
+ return values.length === 1 ? values[0] : undefined;
39
+ };
40
+ const invocation = read(WORKER_INVOCATION_MARKER);
41
+ const workspace = workerWorkspace(read(WORKER_WORKSPACE_MARKER));
42
+ const group = read(WORKER_GROUP_MARKER);
43
+ return { invocation, ...(workspace && group && !/[\0\r\n]/.test(group) ? { workspace, group } : {}) };
44
+ }
@@ -0,0 +1,62 @@
1
+ // Run delivery git operations with explicit identity, signing, transport and a bounded child environment.
2
+ import { execFile } from 'node:child_process';
3
+ import { promisify } from 'node:util';
4
+ import path from 'node:path';
5
+ import { helperEnvironment, HELPER_ENV_ALLOWLIST } from '../process/cli-command.mjs';
6
+ const execute = promisify(execFile);
7
+ export async function command(cwd, executable, args) {
8
+ try {
9
+ const { stdout } = await execute(executable, args, { cwd, encoding: 'utf8', timeout: 120_000, maxBuffer: 8 * 1024 * 1024,
10
+ env: helperEnvironment(process.env, [...HELPER_ENV_ALLOWLIST, 'SSH_AUTH_SOCK', 'GNUPGHOME', 'GPG_TTY']) });
11
+ return stdout.trim();
12
+ }
13
+ catch {
14
+ throw new Error(`Delivery ${path.basename(executable)} operation failed; inspect repository state before retrying`);
15
+ }
16
+ }
17
+ export const git = (cwd, ...args) => command(cwd, 'git', args);
18
+ export function signingEnabled(delivery) {
19
+ const required = delivery?.require_signed_commits || delivery?.merge === 'local-signed';
20
+ const signing = delivery?.signing;
21
+ if (required && !signing?.key)
22
+ throw new Error('Signed delivery requires delivery.signing.key');
23
+ return Boolean(required || (signing?.enforce !== 'tags' && (signing?.key || signing?.key_file)));
24
+ }
25
+ export function commitOptions(delivery, project = process.cwd()) {
26
+ const options = [];
27
+ for (const [key, value] of [['user.name', delivery?.committer?.name], ['user.email', delivery?.committer?.email]]) {
28
+ if (value)
29
+ options.push('-c', `${key}=${value}`);
30
+ }
31
+ if (signingEnabled(delivery)) {
32
+ const signing = delivery.signing;
33
+ if (!signing.key || !delivery?.committer?.name || !delivery.committer.email)
34
+ throw new Error('Signed delivery requires signing.key and committer.name/email');
35
+ const format = signing.format ?? 'openpgp';
36
+ options.push('-c', `gpg.format=${format}`, '-c', `user.signingkey=${signing.key_file ? path.resolve(project, signing.key_file) : signing.key}`, '-c', 'commit.gpgsign=true');
37
+ if (signing.program)
38
+ options.push('-c', `gpg.${format}.program=${/[\\/]/.test(signing.program) ? path.resolve(project, signing.program) : signing.program}`);
39
+ }
40
+ else
41
+ options.push('-c', 'commit.gpgsign=false');
42
+ return options;
43
+ }
44
+ export async function verifyCommit(cwd, sha, delivery, project = cwd) {
45
+ if (!signingEnabled(delivery))
46
+ return;
47
+ const result = await git(cwd, ...commitOptions(delivery, project), 'show', '-s', '--format=%G?%x00%GF%x00%GP%x00%an%x00%ae%x00%cn%x00%ce', sha);
48
+ const [status, key, primaryKey, author, email, committer, committerEmail] = result.split('\0');
49
+ const identity = delivery.committer;
50
+ if (!['G', 'U'].includes(status) || ![key, primaryKey].includes(delivery.signing.key) || author !== identity.name || email !== identity.email || committer !== identity.name || committerEmail !== identity.email) {
51
+ throw new Error('Commit does not satisfy configured signature and author/committer identity');
52
+ }
53
+ }
54
+ export async function push(cwd, project, config, remote, refspec, upstream = false) {
55
+ const helper = config.remotes?.transport?.helper;
56
+ // Helper follows the established helper contract: push options/refspec, configured primary remote owned by helper.
57
+ if (helper)
58
+ await command(cwd, path.resolve(project, helper), [...(upstream ? ['-u'] : []), refspec]);
59
+ else
60
+ await git(cwd, 'push', ...(upstream ? ['-u'] : []), remote, refspec);
61
+ }
62
+ //# sourceMappingURL=git.js.map
@@ -0,0 +1,149 @@
1
+ // Open tracker PRs and execute optional local merges using configured signing and transport policy.
2
+ import { mkdtemp, rm, readFile } from 'node:fs/promises';
3
+ import os from 'node:os';
4
+ import path from 'node:path';
5
+ import { readAiwgConfig, resolveDelivery, resolveRemotes, resolveProject, resolveProjectHandling } from '../config/aiwg-config.js';
6
+ import { sensitiveInputOptions } from '../auth/sensitive-input.js';
7
+ import { deliveryTracker } from './tracker.js';
8
+ import { commitOptions, git, push, signingEnabled, verifyCommit } from './git.js';
9
+ async function branchCommits(cwd, base, head, config) {
10
+ if (!signingEnabled(config.delivery))
11
+ return;
12
+ for (const sha of (await git(cwd, 'rev-list', `${base}..${head}`)).split('\n').filter(Boolean))
13
+ await verifyCommit(cwd, sha, config.delivery);
14
+ }
15
+ export async function openPr(cwd, config, client, options) {
16
+ const policy = resolveDelivery(config.delivery);
17
+ if (policy.mode !== 'pr-required')
18
+ throw new Error('Opening a PR requires delivery.mode=pr-required');
19
+ if (!options.title)
20
+ throw new Error('open requires --title');
21
+ const remote = resolveRemotes(config.remotes).primary;
22
+ const head = options.head ?? await git(cwd, 'symbolic-ref', '--short', 'HEAD');
23
+ await git(cwd, 'check-ref-format', '--branch', head);
24
+ if (head === policy.default_branch)
25
+ throw new Error('PR head must differ from the default branch');
26
+ if (await git(cwd, 'symbolic-ref', '--short', 'HEAD') !== head)
27
+ throw new Error('PR head must be the checked out branch');
28
+ await client.verifyActor();
29
+ const identity = commitOptions(config.delivery, cwd);
30
+ if (options.commitMessageFile) {
31
+ if (!(await git(cwd, 'diff', '--cached', '--name-only')))
32
+ throw new Error('Nothing staged to commit');
33
+ await git(cwd, ...identity, 'commit', '-F', path.resolve(cwd, options.commitMessageFile));
34
+ }
35
+ const sha = await git(cwd, 'rev-parse', '--verify', `refs/heads/${head}^{commit}`);
36
+ const current = await git(cwd, 'rev-parse', 'HEAD');
37
+ if (current !== sha)
38
+ throw new Error('PR head must be the current checked out commit');
39
+ await git(cwd, 'fetch', remote);
40
+ await branchCommits(cwd, `refs/remotes/${remote}/${policy.default_branch}`, sha, config);
41
+ await push(cwd, cwd, config, remote, head, true);
42
+ return client.repositoryRequest('POST', '/pulls', { title: options.title, body: options.body ?? '', head, base: policy.default_branch });
43
+ }
44
+ export async function mergePr(cwd, config, client, number, options = {}) {
45
+ if (!/^[1-9][0-9]*$/.test(number))
46
+ throw new Error('merge requires a positive PR number');
47
+ const policy = resolveDelivery(config.delivery);
48
+ const remotes = resolveRemotes(config.remotes);
49
+ // Resolve invalid signing policy before any tracker or git mutations.
50
+ const identity = commitOptions(config.delivery, cwd);
51
+ const signed = signingEnabled(config.delivery);
52
+ if (signed && policy.merge === 'tracker')
53
+ throw new Error('Configured signing requires a local merge route; ask Steward to set delivery.merge');
54
+ if (options.mirror && (!remotes.secondary.some(remote => remote.name === options.mirror) || !resolveProjectHandling(resolveProject(config.project)).mirror))
55
+ throw new Error('Mirror must be a configured secondary remote permitted by project handling');
56
+ await client.verifyActor();
57
+ const pr = await client.repositoryRequest('GET', `/pulls/${number}`);
58
+ if (pr.state !== 'open')
59
+ throw new Error('PR is not open');
60
+ if (pr.base.ref !== policy.default_branch)
61
+ throw new Error('PR must target the configured default branch');
62
+ if (!/^[a-f0-9]{40,64}$/.test(pr.head.sha))
63
+ throw new Error('Tracker returned an invalid head SHA');
64
+ if (policy.merge === 'tracker') {
65
+ const style = policy.merge_style;
66
+ const method = style === 'squash' ? 'squash' : style === 'rebase-merge' ? 'rebase' : 'merge';
67
+ if (client.provider === 'github' && style === 'fast-forward-only')
68
+ throw new Error('GitHub does not support tracker fast-forward-only merges; use delivery.merge=local');
69
+ const result = await client.repositoryRequest(client.provider === 'github' ? 'PUT' : 'POST', `/pulls/${number}/merge`, client.provider === 'github'
70
+ ? { merge_method: method, sha: pr.head.sha } : { Do: style === 'fast-forward-only' ? 'fast-forward-only' : style === 'rebase-merge' ? 'rebase-merge' : method, head_commit_id: pr.head.sha });
71
+ if (result.merged === false)
72
+ throw new Error('Tracker refused the PR merge');
73
+ return result;
74
+ }
75
+ await git(cwd, 'fetch', remotes.primary);
76
+ await git(cwd, 'fetch', remotes.primary, pr.head.sha);
77
+ const mainRef = `refs/remotes/${remotes.primary}/${policy.default_branch}`;
78
+ const main = await git(cwd, 'rev-parse', mainRef);
79
+ const base = await git(cwd, 'merge-base', pr.head.sha, main);
80
+ const tree = (ref) => git(cwd, 'rev-parse', `${ref}^{tree}`);
81
+ if (await tree(base) !== await tree(main))
82
+ throw new Error('Current main tree differs from branch base; synchronize and verify first');
83
+ if (!(await git(cwd, 'rev-list', `${main}..${pr.head.sha}`)))
84
+ throw new Error('PR has no branch commits to merge');
85
+ await branchCommits(cwd, main, pr.head.sha, config);
86
+ const scratch = await mkdtemp(path.join(os.tmpdir(), 'aiwg-merge-'));
87
+ const worktree = path.join(scratch, 'worktree');
88
+ let added = false;
89
+ try {
90
+ await git(cwd, 'worktree', 'add', '--detach', worktree, main);
91
+ added = true;
92
+ await git(worktree, ...identity, 'merge', '--no-ff', ...(signed ? ['-S'] : []), '-m', `merge: ${pr.title} (#${number})`, pr.head.sha);
93
+ const merged = await git(worktree, 'rev-parse', 'HEAD');
94
+ if (await tree(merged) !== await tree(pr.head.sha))
95
+ throw new Error('Merge tree differs from verified PR head');
96
+ await verifyCommit(worktree, merged, config.delivery, cwd);
97
+ // Refuse a changed PR or main before push; the ordinary push also rejects a concurrent non-fast-forward update.
98
+ const latest = await client.repositoryRequest('GET', `/pulls/${number}`);
99
+ if (latest.state !== 'open' || latest.head.sha !== pr.head.sha || latest.base.ref !== pr.base.ref)
100
+ throw new Error('PR changed during merge; retry after verification');
101
+ await git(cwd, 'fetch', remotes.primary);
102
+ if (await git(cwd, 'rev-parse', mainRef) !== main)
103
+ throw new Error('Main changed during merge; synchronize and verify first');
104
+ await push(worktree, cwd, config, remotes.primary, `${merged}:refs/heads/${policy.default_branch}`);
105
+ await client.repositoryRequest('PATCH', `/pulls/${number}`, { state: 'closed' });
106
+ await git(cwd, 'fetch', remotes.primary);
107
+ if (await git(cwd, 'rev-parse', mainRef) !== merged)
108
+ throw new Error('Remote default branch differs from the local merge');
109
+ if (options.mirror)
110
+ await git(cwd, 'push', options.mirror, `${merged}:refs/heads/${policy.default_branch}`);
111
+ return { number: Number(number), merged, signed, mode: policy.merge };
112
+ }
113
+ finally {
114
+ try {
115
+ if (added)
116
+ await git(cwd, 'worktree', 'remove', '--force', worktree);
117
+ }
118
+ finally {
119
+ await rm(scratch, { recursive: true, force: true });
120
+ }
121
+ }
122
+ }
123
+ export async function main(args, cwd = process.cwd()) {
124
+ const config = await readAiwgConfig(cwd);
125
+ if (!config)
126
+ throw new Error('PR delivery requires .aiwg/aiwg.config');
127
+ const flags = new Map();
128
+ const positional = [];
129
+ const allowed = ['title', 'body-file', 'head', 'commit-message-file', 'mirror', 'repo', 'api-url', 'token-store', 'token-env'];
130
+ for (let i = 0; i < args.length; i++) {
131
+ if (!args[i].startsWith('--')) {
132
+ positional.push(args[i]);
133
+ continue;
134
+ }
135
+ const key = args[i].slice(2);
136
+ if (!allowed.includes(key) || !args[i + 1] || args[i + 1].startsWith('--') || flags.has(key))
137
+ throw new Error(`Invalid PR option: --${key}`);
138
+ flags.set(key, args[++i]);
139
+ }
140
+ if (!['open', 'merge'].includes(positional[0]) || positional.length !== (positional[0] === 'merge' ? 2 : 1))
141
+ throw new Error('Usage: aiwg run skill aiwg-pr -- open --title <title> --body-file <path> [--commit-message-file <path>] | merge <number> [--mirror <remote>]');
142
+ const client = await deliveryTracker(cwd, config, { repo: flags.get('repo'), apiUrl: flags.get('api-url'), source: sensitiveInputOptions(args, 'token') });
143
+ const options = { title: flags.get('title'), head: flags.get('head'), commitMessageFile: flags.get('commit-message-file'), mirror: flags.get('mirror'),
144
+ body: flags.has('body-file') ? await readFile(path.resolve(cwd, flags.get('body-file')), 'utf8') : undefined };
145
+ const result = positional[0] === 'open' ? await openPr(cwd, config, client, options) : await mergePr(cwd, config, client, positional[1], options);
146
+ console.log(JSON.stringify(result, null, 2));
147
+ return 0;
148
+ }
149
+ //# sourceMappingURL=pr.js.map
@@ -0,0 +1,33 @@
1
+ import { resolveRemotes } from '../config/aiwg-config.js';
2
+ import { LiveIssueClient } from '../issues/live.js';
3
+ import { trackerToken } from '../issues/tracker-policy.js';
4
+ import { git } from './git.js';
5
+ export async function deliveryTracker(cwd, config, options = {}) {
6
+ const remotes = resolveRemotes(config.remotes);
7
+ if (remotes.issue_provider === 'local' || remotes.issue_tracker === 'local')
8
+ throw new Error('PR and external issue writes require an external tracker');
9
+ let provider = remotes.issue_provider;
10
+ let repo = options.repo;
11
+ let apiUrl = options.apiUrl;
12
+ if (!repo || !apiUrl || !provider) {
13
+ const remote = remotes.issue_tracker;
14
+ const url = remote.includes('://') || remote.includes('@') ? remote : await git(cwd, 'remote', 'get-url', remote);
15
+ const normalized = url.replace(/^([^@]+@)([^:]+):/, 'ssh://$1$2/');
16
+ let parsed;
17
+ try {
18
+ parsed = new URL(normalized);
19
+ }
20
+ catch {
21
+ throw new Error('Cannot resolve tracker remote; supply --repo and --api-url with an explicit issue_provider');
22
+ }
23
+ if ((parsed.protocol === 'https:' || parsed.protocol === 'http:') && (parsed.username || parsed.password))
24
+ throw new Error('Tracker remote URLs must not contain credentials');
25
+ provider ??= parsed.hostname === 'github.com' ? 'github' : 'gitea';
26
+ repo ??= parsed.pathname.replace(/^\//, '').replace(/\.git$/, '');
27
+ const protocol = parsed.protocol === 'http:' ? 'http:' : 'https:';
28
+ apiUrl ??= provider === 'github' ? parsed.hostname === 'github.com' ? 'https://api.github.com' : `${protocol}//${parsed.host}/api/v3` : `${protocol}//${parsed.host}/api/v1`;
29
+ }
30
+ const token = await trackerToken(provider, remotes.tracker_actor, options.source);
31
+ return new LiveIssueClient({ provider, repo, apiUrl, token, actor: remotes.tracker_actor });
32
+ }
33
+ //# sourceMappingURL=tracker.js.map
@@ -137,7 +137,7 @@ export function interviewQuestions(context, answers = {}) {
137
137
  questions[questions.length - 1].questionId = questionId('locations', 'credential-source', project.root, 'jev');
138
138
  add('capabilities', 'jev-options', 'Optional Jev settings as JSON: region, endpoint, verify. Verification sends a billable request at apply.', null, [null], '--region <r> --endpoint <url> --verify', 'policy', project.root, 'jev', true);
139
139
  }
140
- add('capabilities', 'signing', 'Require signed delivery commits?', false, [true, false], '--require-signed-commits --signing-format --signing-key --signing-enforce', 'policy', project.root, undefined, true);
140
+ add('capabilities', 'signing', 'Optional: require signed delivery commits? Signed local merges are recommended where permitted; skip preserves unsigned delivery. Set up with aiwg steward signed-merges.', false, [true, false], '--require-signed-commits --signing-format --signing-key --signing-enforce', 'policy', project.root, undefined, true);
141
141
  add('capabilities', 'delivery', 'Delivery mode and branch protections.', { mode: 'pr-required', force_push_policy: 'never' }, [false, { mode: 'pr-required', force_push_policy: 'never' }], '--delivery-mode --default-branch --require-ci-green --auto-close-issues --issue-comment-on-cycle --force-push-policy', 'policy', project.root, undefined, true);
142
142
  add('capabilities', 'tracker', 'Issue tracker provider and remotes.', null, ['gitea', 'github', 'local'].map(issue_provider => ({ issue_provider })), '--issue-provider gitea|github|local', 'policy', project.root, undefined, !context.unknownRemote, !!context.unknownRemote);
143
143
  }
@@ -38,6 +38,7 @@ import { mergeClaudeAttribution, undoClaudeAttribution } from './claude-attribut
38
38
  const HOOK_SCRIPTS = [
39
39
  { file: 'aiwg-permissions.cjs', events: { PermissionRequest: undefined } },
40
40
  { file: 'aiwg-session.cjs', events: { SessionStart: undefined } },
41
+ { file: 'aiwg-prompt-discovery.cjs', events: { UserPromptSubmit: undefined } },
41
42
  {
42
43
  file: 'aiwg-trace.cjs',
43
44
  events: { SubagentStart: 'start', SubagentStop: 'stop' },
@@ -11,7 +11,6 @@
11
11
  import { getRegistry, createRegistry } from './registry.js';
12
12
  import { CapabilityIndex } from './capability-index.js';
13
13
  import { commandDefinitions } from './commands/definitions.js';
14
- import { allHandlers } from '../cli/handlers/index.js';
15
14
  /**
16
15
  * Load and populate the registry
17
16
  *
@@ -41,6 +40,7 @@ import { allHandlers } from '../cli/handlers/index.js';
41
40
  */
42
41
  export async function loadRegistry(options) {
43
42
  const { registry = createRegistry(), indexCapabilities = false } = options || {};
43
+ const allHandlers = options?.handlers ?? (await import('../cli/handlers/index.js')).allHandlers;
44
44
  // Register all command definitions
45
45
  for (const definition of commandDefinitions) {
46
46
  registry.register(definition);
@@ -100,6 +100,7 @@ export async function getLoadedRegistry() {
100
100
  return loadRegistry({ registry: globalRegistry });
101
101
  }
102
102
  // Already loaded - just build handler map
103
+ const { allHandlers } = await import('../cli/handlers/index.js');
103
104
  const handlerMap = linkHandlers(allHandlers);
104
105
  return {
105
106
  registry: globalRegistry,