@aiwg/cli 2026.10.19 → 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.
- package/README.md +1 -0
- package/agentic/code/providers/flue/README.md +2 -1
- package/dist/src/artifacts/cli.js +3 -2
- package/dist/src/artifacts/discover-facets.js +2 -0
- package/dist/src/artifacts/discover-session-facets.js +14 -0
- package/dist/src/artifacts/fortemi-core-query-adapter.js +4 -4
- package/dist/src/artifacts/framework-capabilities.js +7 -3
- package/dist/src/artifacts/index-builder.js +2 -3
- package/dist/src/artifacts/query-engine-discover-output.js +3 -3
- package/dist/src/artifacts/query-engine-discover.js +61 -14
- package/dist/src/artifacts/query-engine-entries.js +52 -9
- package/dist/src/artifacts/query-engine-installation.js +27 -0
- package/dist/src/artifacts/query-engine-rules.js +1 -2
- package/dist/src/artifacts/query-engine-scoring.js +33 -31
- package/dist/src/artifacts/query-engine-show-card.js +6 -2
- package/dist/src/artifacts/query-engine-show.js +2 -2
- package/dist/src/artifacts/relations.js +17 -10
- package/dist/src/cli/handlers/bundle-declaration.js +55 -0
- package/dist/src/cli/handlers/bundle-deployment-mode.js +71 -0
- package/dist/src/cli/handlers/bundle-hash-prune.js +37 -0
- package/dist/src/cli/handlers/bundle-reconciliation.js +140 -0
- package/dist/src/cli/handlers/checkpoint.js +143 -0
- package/dist/src/cli/handlers/help.js +1 -0
- package/dist/src/cli/handlers/index.js +4 -2
- package/dist/src/cli/handlers/models-resource-sample.js +7 -3
- package/dist/src/cli/handlers/ralph-launcher.js +1 -1
- package/dist/src/cli/handlers/refresh-bundles.js +35 -0
- package/dist/src/cli/handlers/refresh-rule-inventory.js +10 -0
- package/dist/src/cli/handlers/refresh.js +15 -52
- package/dist/src/cli/handlers/remove-bundled.js +7 -4
- package/dist/src/cli/handlers/remove-flue-modules.js +19 -0
- package/dist/src/cli/handlers/remove-historical-bundle.js +18 -0
- package/dist/src/cli/handlers/remove.js +8 -0
- package/dist/src/cli/handlers/script-runner.js +12 -1
- package/dist/src/cli/handlers/steward-signing.js +44 -0
- package/dist/src/cli/handlers/steward.js +5 -0
- package/dist/src/cli/handlers/subcommands-list-format.js +4 -4
- package/dist/src/cli/handlers/update.js +18 -8
- package/dist/src/cli/handlers/use-additive-bundles.js +87 -0
- package/dist/src/cli/handlers/use-bundle-counts.js +5 -1
- package/dist/src/cli/handlers/use-owned-counts.js +75 -0
- package/dist/src/cli/handlers/use-provider-results.js +17 -0
- package/dist/src/cli/handlers/use.js +53 -114
- package/dist/src/cli/router.js +12 -2
- package/dist/src/cli/services/deployment-verification.js +2 -1
- package/dist/src/cli/user-scope-mirror.js +3 -1
- package/dist/src/config/aiwg-config.js +15 -6
- package/dist/src/config/cli.js +1 -0
- package/dist/src/config/delivery-validation.js +21 -0
- package/dist/src/config/framework-aliases.js +14 -0
- package/dist/src/config/host-resource-report.d.mts +1 -1
- package/dist/src/config/host-resource-report.mjs +23 -4
- package/dist/src/config/host-resource-runtime.d.mts +8 -0
- package/dist/src/config/host-resource-runtime.mjs +67 -24
- package/dist/src/config/index-graph-overrides.js +4 -0
- package/dist/src/config/installed-selection.js +9 -1
- package/dist/src/config/installed-validation.js +35 -0
- package/dist/src/config/worker-attribution.d.mts +7 -0
- package/dist/src/config/worker-attribution.mjs +44 -0
- package/dist/src/delivery/git.js +62 -0
- package/dist/src/delivery/pr.js +149 -0
- package/dist/src/delivery/tracker.js +33 -0
- package/dist/src/discovery/interview.js +1 -1
- package/dist/src/extensions/claude-hooks-installer.js +1 -0
- package/dist/src/extensions/loader.js +2 -1
- package/dist/src/extensions/project-local-doctor.js +1 -1
- package/dist/src/extensions/project-local-remove.js +3 -3
- package/dist/src/issues/cli.js +12 -3
- package/dist/src/issues/external-cli.js +76 -0
- package/dist/src/issues/live.js +18 -1
- package/dist/src/issues/tracker-policy.js +17 -0
- package/dist/src/mcp/cli.mjs +12 -7
- package/dist/src/mcp/helpers.mjs +5 -1
- package/dist/src/mcp/http-options.mjs +101 -0
- package/dist/src/mcp/http-tools.mjs +51 -0
- package/dist/src/mcp/http-transport.mjs +201 -0
- package/dist/src/mcp/server.mjs +9 -7
- package/dist/src/mcp/tool-context.mjs +25 -0
- package/dist/src/mcp/tools/orchestration.mjs +2 -1
- package/dist/src/mcp/tools/worker-invoke.mjs +2 -1
- package/dist/src/mcp/tools/worker-stdin-runtime.mjs +12 -0
- package/dist/src/models/conductor-data-policy.d.mts +3 -2
- package/dist/src/models/conductor-data-policy.mjs +94 -5
- package/dist/src/models/worker-plan.js +3 -3
- package/dist/src/models/worker-selection-policy.js +2 -1
- package/dist/src/providers/deployment-lock.js +77 -0
- package/dist/src/providers/deployment-ownership.d.mts +12 -2
- package/dist/src/providers/deployment-ownership.mjs +127 -19
- package/dist/src/providers/deployment-preservation.d.mts +6 -0
- package/dist/src/providers/deployment-preservation.mjs +113 -0
- package/dist/src/providers/deployment-removal.js +4 -2
- package/dist/src/providers/flue-package-mode.js +19 -0
- package/dist/src/providers/provider-definitions.js +4 -0
- package/dist/src/providers/skill-ownership.mjs +1 -0
- package/dist/src/research/reference-match.js +4 -0
- package/dist/src/serve/worker-invocation-preparation.js +3 -1
- package/dist/src/serve/worker-invocation.js +2 -0
- package/dist/src/skills/run.js +5 -0
- package/dist/src/smiths/hook-bridge/codex-translator.js +3 -1
- package/dist/src/smiths/hook-bridge/hermes-translator.js +3 -1
- package/dist/src/smiths/hook-bridge/prompt-discovery-gaps.js +6 -0
- package/package.json +5 -2
- package/schemas/models/model-config-compatibility.v1.schema.json +4 -0
- package/tools/agents/deploy-agents.mjs +21 -1
- package/tools/agents/deploy-options.mjs +2 -0
- package/tools/agents/providers/base-contract.mjs +7 -1
- package/tools/agents/providers/base-inventory.mjs +41 -14
- package/tools/agents/providers/base-kernel-skills.mjs +9 -5
- package/tools/agents/providers/base-migrations.mjs +1 -0
- package/tools/agents/providers/base-skill-copy.mjs +9 -1
- package/tools/agents/providers/base.mjs +1 -1
- package/tools/agents/providers/claude.mjs +2 -1
- package/tools/agents/providers/codex.mjs +5 -1
- package/tools/agents/providers/conductor-data-guard.mjs +35 -11
- package/tools/agents/providers/flue-bundles.mjs +42 -0
- package/tools/agents/providers/flue-cloudflare.mjs +20 -0
- package/tools/agents/providers/flue-project.mjs +45 -6
- package/tools/agents/providers/flue-skill-copy.mjs +25 -0
- package/tools/agents/providers/flue-skills.mjs +45 -0
- package/tools/agents/providers/flue-specialists.mjs +36 -18
- package/tools/agents/providers/flue-validation.mjs +14 -0
- package/tools/agents/providers/flue.mjs +12 -8
- package/tools/agents/providers/hermes-skill-lifecycle.mjs +1 -0
- package/tools/agents/providers/muse-hooks.mjs +4 -0
- package/tools/agents/providers/muse-prompt-discovery.mjs +22 -0
- package/tools/agents/providers/provider-prepare-coordinator.mjs +15 -10
- package/tools/agents/providers/rule-delivery-surface.mjs +18 -1
- package/tools/agents/providers/rule-deployment-commit.mjs +24 -0
- package/tools/agents/providers/rule-deployment-prepare.mjs +4 -0
- package/tools/agents/providers/skill-copy-prune.mjs +49 -0
- package/tools/agents/providers/stale-artifact-prune.mjs +10 -8
- package/tools/ralph-external/lib/worker-capture.mjs +157 -0
- package/tools/ralph-external/lib/worker-health.mjs +3 -0
- package/tools/ralph-external/lib/worker-invocation-processes.mjs +9 -6
- package/tools/ralph-external/lib/worker-launch-cli.mjs +10 -1
- package/tools/ralph-external/lib/worker-process-identity.mjs +30 -0
- package/tools/ralph-external/lib/worker-retry-evidence.mjs +87 -6
- package/tools/ralph-external/lib/worker-termination.mjs +56 -6
- package/tools/ralph-external/process-monitor.mjs +12 -18
- package/tools/ralph-external/session-launcher.mjs +43 -29
- package/tools/skills/codex-skill-metadata.mjs +22 -0
- package/tools/skills/deploy-skills-codex.mjs +8 -7
- package/vscode-extension/schemas/aiwg.config.v1.json +59 -19
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
export function validateDeliverySettings(config) {
|
|
2
|
+
const errors = [];
|
|
3
|
+
const delivery = config.delivery;
|
|
4
|
+
if (delivery?.merge !== undefined && !['local-signed', 'local', 'tracker'].includes(delivery.merge))
|
|
5
|
+
errors.push('delivery.merge must be local-signed, local, or tracker');
|
|
6
|
+
for (const name of ['tracker_actor', 'customer_tracker_actor']) {
|
|
7
|
+
const credential = config.remotes?.[name]?.credential;
|
|
8
|
+
if (credential !== undefined) {
|
|
9
|
+
const entries = credential && typeof credential === 'object' ? Object.entries(credential) : [];
|
|
10
|
+
if (entries.length !== 1 || !entries.every(([key, value]) => typeof value === 'string' &&
|
|
11
|
+
(key === 'env' ? /^[A-Za-z_][A-Za-z0-9_]*$/.test(value) : key === 'store' && /^[A-Za-z0-9][A-Za-z0-9_.-]{0,127}$/.test(value)))) {
|
|
12
|
+
errors.push(`remotes.${name}.credential requires exactly one store or env reference`);
|
|
13
|
+
}
|
|
14
|
+
}
|
|
15
|
+
}
|
|
16
|
+
if (delivery?.merge === 'local-signed' && (!delivery.signing?.key || !delivery.committer?.name || !delivery.committer.email)) {
|
|
17
|
+
errors.push('delivery.merge=local-signed requires signing.key and committer.name/email');
|
|
18
|
+
}
|
|
19
|
+
return errors;
|
|
20
|
+
}
|
|
21
|
+
//# sourceMappingURL=delivery-validation.js.map
|
|
@@ -8,5 +8,19 @@ export const REGISTRY_ID_TO_USE_NAME = {
|
|
|
8
8
|
'media-curator': 'media-curator',
|
|
9
9
|
'research-complete': 'research',
|
|
10
10
|
'forensics-complete': 'forensics',
|
|
11
|
+
dfir: 'forensics',
|
|
12
|
+
'ops-complete': 'ops',
|
|
13
|
+
'validation-complete': 'validation',
|
|
11
14
|
};
|
|
15
|
+
// Reverse aliases without letting a secondary alias (dfir) replace the canonical ID.
|
|
16
|
+
const USE_NAME_TO_REGISTRY_ID = {
|
|
17
|
+
...Object.fromEntries(Object.entries(REGISTRY_ID_TO_USE_NAME).reverse().map(([id, alias]) => [alias, id])),
|
|
18
|
+
general: 'writing-quality',
|
|
19
|
+
writing: 'writing-quality',
|
|
20
|
+
};
|
|
21
|
+
/** Resolve a use name or legacy alias to its canonical bundle directory. */
|
|
22
|
+
export function frameworkRegistryId(name) {
|
|
23
|
+
const useName = REGISTRY_ID_TO_USE_NAME[name] ?? name;
|
|
24
|
+
return USE_NAME_TO_REGISTRY_ID[useName] ?? name;
|
|
25
|
+
}
|
|
12
26
|
//# sourceMappingURL=framework-aliases.js.map
|
|
@@ -12,7 +12,7 @@ export interface HostResourceReport {
|
|
|
12
12
|
slots: number;
|
|
13
13
|
ok: boolean;
|
|
14
14
|
limits: Array<{ threshold: string; slots: number }>;
|
|
15
|
-
failures: Array<{ signal: string; reason: string; actual?: number; threshold?: number }>;
|
|
15
|
+
failures: Array<{ signal: string; reason: string; code?: 'OG_HOST_ATTRIBUTION' | 'OG_HOST_CAPACITY'; actual?: number; threshold?: number }>;
|
|
16
16
|
counting?: string;
|
|
17
17
|
limitingThreshold?: string;
|
|
18
18
|
groups: Array<{ group: string; maxParallel: number | null; slots: number | null; reason: string }>;
|
|
@@ -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,
|
|
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 {
|
|
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
|
-
|
|
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
|
|
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
|
|
116
|
-
|
|
117
|
-
if (!invocation)
|
|
118
|
-
|
|
119
|
-
|
|
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
|
-
|
|
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
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
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
|
-
|
|
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
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
// Keep automatic redeployment from changing the explicitly installed selection.
|
|
2
2
|
import { AsyncLocalStorage } from 'node:async_hooks';
|
|
3
3
|
import { resolve } from 'node:path';
|
|
4
|
-
import { REGISTRY_ID_TO_USE_NAME } from './framework-aliases.js';
|
|
4
|
+
import { REGISTRY_ID_TO_USE_NAME, frameworkRegistryId } from './framework-aliases.js';
|
|
5
5
|
const selection = new AsyncLocalStorage();
|
|
6
6
|
export function withInstalledSelection(project, installed, deploy) {
|
|
7
7
|
return selection.run({ project: resolve(project), installed: structuredClone(installed) }, deploy);
|
|
@@ -19,4 +19,12 @@ export function preserveInstalledSelection(project, config) {
|
|
|
19
19
|
]));
|
|
20
20
|
return guarded;
|
|
21
21
|
}
|
|
22
|
+
/** Automatic framework passes cannot reinstall a local bundle the operator undeclared. */
|
|
23
|
+
export function permitsBundleDeployment(project, id, provider) {
|
|
24
|
+
const current = selection.getStore();
|
|
25
|
+
if (!current || current.project !== resolve(project) || current.installed === undefined)
|
|
26
|
+
return true;
|
|
27
|
+
const entry = Object.entries(current.installed).find(([key]) => frameworkRegistryId(key) === frameworkRegistryId(id))?.[1];
|
|
28
|
+
return Boolean(entry?.deployedTo?.[provider]);
|
|
29
|
+
}
|
|
22
30
|
//# sourceMappingURL=installed-selection.js.map
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
// Validate new declarations and deployment writes without rejecting historical reads.
|
|
2
|
+
const object = (value) => !!value && typeof value === 'object' && !Array.isArray(value);
|
|
3
|
+
const kinds = ['agents', 'commands', 'skills', 'rules'];
|
|
4
|
+
export function validateInstalled(installed) {
|
|
5
|
+
if (installed === undefined)
|
|
6
|
+
return;
|
|
7
|
+
if (!object(installed))
|
|
8
|
+
throw new Error('installed must be an object');
|
|
9
|
+
for (const [id, entry] of Object.entries(installed)) {
|
|
10
|
+
if (!object(entry) || !object(entry.deployedTo))
|
|
11
|
+
throw new Error(`installed.${id}.deployedTo must be an object`);
|
|
12
|
+
let deployed = false;
|
|
13
|
+
for (const [provider, counts] of Object.entries(entry.deployedTo)) {
|
|
14
|
+
if (!object(counts))
|
|
15
|
+
throw new Error(`installed.${id}.deployedTo.${provider} must be an object`);
|
|
16
|
+
for (const flag of ['copy', 'skipUtils', 'kernelOnly']) {
|
|
17
|
+
if (counts[flag] !== undefined && typeof counts[flag] !== 'boolean')
|
|
18
|
+
throw new Error(`installed.${id}.deployedTo.${provider}.${flag} must be boolean`);
|
|
19
|
+
}
|
|
20
|
+
if (counts.package !== undefined && (typeof counts.package !== 'boolean' || provider !== 'flue'))
|
|
21
|
+
throw new Error(`installed.${id}.deployedTo.${provider}.package requires Flue and a boolean`);
|
|
22
|
+
if (!Object.keys(counts).some(key => !['copy', 'package', 'skipUtils', 'kernelOnly'].includes(key)))
|
|
23
|
+
continue;
|
|
24
|
+
if (kinds.some(kind => !Number.isSafeInteger(counts[kind]) || counts[kind] < 0)) {
|
|
25
|
+
throw new Error(`installed.${id}.deployedTo.${provider} requires all four nonnegative artifact counts or {}`);
|
|
26
|
+
}
|
|
27
|
+
deployed = true;
|
|
28
|
+
}
|
|
29
|
+
if (deployed || ['version', 'source', 'installedAt'].some(key => entry[key] !== undefined)) {
|
|
30
|
+
if (['version', 'source', 'installedAt'].some(key => typeof entry[key] !== 'string' || !entry[key]))
|
|
31
|
+
throw new Error(`installed.${id} requires version, source and installedAt after deployment`);
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
//# sourceMappingURL=installed-validation.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
|