@aiwg/cli 2026.10.14 → 2026.10.16
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/agentic/code/addons/aiwg-utils/rules/anti-laziness.core.md +13 -0
- package/agentic/code/addons/aiwg-utils/rules/anti-laziness.md +118 -0
- package/agentic/code/providers/pi/aiwg-bridge.ts +45 -7
- package/dist/src/artifacts/citation-parser.js +7 -6
- package/dist/src/artifacts/corpus-tools/citation-densify.js +4 -2
- package/dist/src/artifacts/corpus-tools/cli.js +37 -0
- package/dist/src/artifacts/corpus-tools/discovery-log.js +27 -25
- package/dist/src/artifacts/corpus-tools/expand-cli.js +90 -0
- package/dist/src/artifacts/corpus-tools/expand-dates.js +107 -0
- package/dist/src/artifacts/corpus-tools/expand-queue.js +41 -0
- package/dist/src/artifacts/corpus-tools/expand-review.js +104 -0
- package/dist/src/artifacts/corpus-tools/expand-state.js +56 -0
- package/dist/src/artifacts/corpus-tools/expand.js +124 -0
- package/dist/src/artifacts/corpus-tools/induction-audit.js +7 -6
- package/dist/src/artifacts/corpus-tools/integrity-scan.js +3 -3
- package/dist/src/artifacts/corpus-tools/radar-shared.js +7 -9
- package/dist/src/artifacts/corpus-tools/ref-files.js +11 -0
- package/dist/src/artifacts/corpus-tools/resolve-cli.js +99 -0
- package/dist/src/artifacts/corpus-tools/resolve-corpus.js +41 -0
- package/dist/src/artifacts/corpus-tools/resolve.js +119 -0
- package/dist/src/artifacts/corpus-tools/retrieval-lab.js +2 -1
- package/dist/src/artifacts/corpus-tools/sidecar-lint.js +4 -4
- package/dist/src/artifacts/corpus-tools/sidecar-repair.js +2 -1
- package/dist/src/artifacts/corpus-views/ref-parser.js +3 -17
- package/dist/src/artifacts/graph-query.js +5 -3
- package/dist/src/artifacts/hybrid-query.js +11 -2
- package/dist/src/artifacts/index-refresh.js +2 -0
- package/dist/src/cli/handlers/daemon.js +17 -1
- package/dist/src/cli/handlers/doctor-args.js +45 -0
- package/dist/src/cli/handlers/doctor-help.js +8 -3
- package/dist/src/cli/handlers/index.js +2 -2
- package/dist/src/cli/handlers/models-resource-sample.js +10 -0
- package/dist/src/cli/handlers/models.js +3 -2
- package/dist/src/cli/handlers/regenerate.js +8 -16
- package/dist/src/cli/handlers/sessions.js +7 -7
- package/dist/src/cli/handlers/subcommands.js +8 -0
- package/dist/src/cli/handlers/update.js +157 -0
- package/dist/src/cli/handlers/use.js +14 -4
- package/dist/src/cli/handlers/utilities.js +3 -586
- package/dist/src/cli/handlers/utility-doctor.js +412 -0
- package/dist/src/cli/services/deployment-verification.js +0 -1
- package/dist/src/config/aiwg-config.js +2 -1
- package/dist/src/config/authorization-cli.js +7 -3
- package/dist/src/config/dispatch-thresholds-runtime.d.mts +3 -2
- package/dist/src/config/dispatch-thresholds-runtime.mjs +17 -7
- package/dist/src/config/framework-aliases.js +12 -0
- package/dist/src/config/host-resource-report.d.mts +19 -0
- package/dist/src/config/host-resource-report.mjs +80 -0
- package/dist/src/config/host-resource-runtime.d.mts +34 -0
- package/dist/src/config/host-resource-runtime.mjs +293 -0
- package/dist/src/config/installed-selection.js +22 -0
- package/dist/src/config/worker-context.js +33 -4
- package/dist/src/config/worker-invocation-marker.d.mts +1 -0
- package/dist/src/config/worker-invocation-marker.mjs +2 -0
- package/dist/src/decision/heldout/access.js +74 -0
- package/dist/src/decision/heldout/calibration.js +1 -0
- package/dist/src/decision/heldout/collector.js +9 -2
- package/dist/src/effects/verifiers/file.js +22 -5
- package/dist/src/extensions/claude-attribution.js +82 -0
- package/dist/src/extensions/claude-hooks-installer.js +115 -69
- package/dist/src/extensions/commands/daemon.js +109 -0
- package/dist/src/extensions/commands/definitions.js +5 -89
- package/dist/src/features/catalog.js +1 -1
- package/dist/src/gates/evaluate.js +2 -2
- package/dist/src/gates/heldout.js +52 -0
- package/dist/src/gates/index.js +2 -1
- package/dist/src/lint/check-patterns.js +163 -0
- package/dist/src/lint/checks.js +268 -0
- package/dist/src/lint/reference-resolution.js +54 -0
- package/dist/src/lint/runner.js +3 -465
- package/dist/src/mcp/helpers.mjs +11 -1
- package/dist/src/memory/project-registry.js +44 -4
- package/dist/src/models/worker-installation-store.mjs +228 -0
- package/dist/src/models/worker-installation.mjs +7 -162
- package/dist/src/models/worker-plan.js +36 -5
- package/dist/src/models/wrapper-deployment.js +25 -12
- package/dist/src/models/wrapper-enforcement.js +47 -7
- package/dist/src/network-analysis/research.js +2 -1
- package/dist/src/policy/hitl-check.js +14 -4
- package/dist/src/policy/hitl-consume.js +54 -0
- package/dist/src/policy/hitl-receipt.js +2 -0
- package/dist/src/policy/hitl.js +11 -3
- package/dist/src/providers/provider-context-contracts.js +162 -0
- package/dist/src/providers/provider-definition-schema.js +136 -0
- package/dist/src/providers/provider-definitions.js +8 -1298
- package/dist/src/providers/provider-seeds-1.js +360 -0
- package/dist/src/providers/provider-seeds-2.js +387 -0
- package/dist/src/providers/provider-seeds-3.js +262 -0
- package/dist/src/research/clients/arxiv.js +14 -34
- package/dist/src/research/clients/base.js +53 -26
- package/dist/src/research/clients/crossref.js +9 -1
- package/dist/src/research/clients/semantic-scholar.js +73 -44
- package/dist/src/research/identity.js +117 -0
- package/dist/src/research/index.js +1 -0
- package/dist/src/research/query-cli.js +3 -87
- package/dist/src/research/query-options.js +87 -0
- package/dist/src/research/reference-match.js +135 -0
- package/dist/src/research/services/acquisition.js +9 -7
- package/dist/src/research/services/citation.js +5 -2
- package/dist/src/research/types.js +2 -0
- package/dist/src/rules/core-startup.d.mts +2 -0
- package/dist/src/rules/core-startup.mjs +31 -0
- package/dist/src/serve/mission-conductor.js +48 -4
- package/dist/src/sessions/adapters/grok-build-native.js +23 -0
- package/dist/src/sessions/adapters/grok-build.js +14 -7
- package/dist/src/sessions/workspace-discovery.js +5 -5
- package/dist/src/smiths/context-pipeline/agents-md.js +34 -0
- package/dist/src/smiths/context-pipeline/aiwg-md.js +19 -46
- package/dist/src/smiths/context-pipeline/bridge-ownership.js +50 -0
- package/dist/src/smiths/context-pipeline/claude-hook.js +1 -1
- package/dist/src/smiths/context-pipeline/code-regions.js +28 -0
- package/dist/src/smiths/context-pipeline/finalization.js +81 -51
- package/dist/src/smiths/context-pipeline/generator.js +49 -114
- package/dist/src/smiths/context-pipeline/managed-hook.js +11 -1
- package/dist/src/smiths/context-pipeline/muse-bridge.js +2 -2
- package/dist/src/smiths/context-pipeline/provider-policy.js +6 -12
- package/dist/src/smiths/context-pipeline/workspace-audit.js +299 -0
- package/dist/src/smiths/context-pipeline/workspace-bootstrap.js +148 -0
- package/dist/src/smiths/context-pipeline/workspace-context-shared.js +111 -0
- package/dist/src/smiths/context-pipeline/workspace-context.js +8 -1373
- package/dist/src/smiths/context-pipeline/workspace-doctor.js +192 -0
- package/dist/src/smiths/context-pipeline/workspace-document.js +201 -0
- package/dist/src/smiths/context-pipeline/workspace-extraction.js +205 -0
- package/dist/src/smiths/context-pipeline/workspace-migration.js +250 -0
- package/package.json +13 -2
- package/schemas/decision/D29Study.v10.schema.json +65 -0
- package/tools/agents/deploy-agents.mjs +12 -123
- package/tools/agents/providers/antigravity.mjs +1 -1
- package/tools/agents/providers/claude-post-deploy.mjs +12 -1
- package/tools/agents/providers/context-write.mjs +16 -0
- package/tools/agents/providers/grok-build.mjs +8 -5
- package/tools/agents/providers/hermes-skill-lifecycle.mjs +144 -0
- package/tools/agents/providers/hermes-startup.mjs +209 -0
- package/tools/agents/providers/hermes.mjs +9 -359
- package/tools/agents/providers/model-wrapper.mjs +5 -1
- package/tools/agents/providers/muse.mjs +3 -3
- package/tools/agents/providers/pi.mjs +4 -2
- package/tools/agents/providers/rule-delivery-surface.mjs +332 -0
- package/tools/agents/providers/rule-delivery.mjs +20 -1346
- package/tools/agents/providers/rule-deployment-commit.mjs +144 -0
- package/tools/agents/providers/rule-deployment-prepare.mjs +452 -0
- package/tools/agents/providers/rule-deployment-state.mjs +300 -0
- package/tools/agents/providers/rule-presentation.mjs +13 -4
- package/tools/agents/providers/rule-projection.mjs +119 -0
- package/tools/agents/providers/rule-startup.mjs +70 -0
- package/tools/agents/providers/stale-artifact-prune.mjs +128 -0
- package/tools/agents/providers/warp.mjs +2 -2
- package/tools/agents/providers/windsurf.mjs +11 -57
- package/tools/daemon/README.md +511 -0
- package/tools/daemon/adapters/base-adapter.mjs +84 -0
- package/tools/daemon/adapters/webhook-adapter.mjs +107 -0
- package/tools/daemon/agent-supervisor.mjs +299 -0
- package/tools/daemon/automation-engine.mjs +310 -0
- package/tools/daemon/autonomous-engine.mjs +346 -0
- package/tools/daemon/behavior-loader.mjs +316 -0
- package/tools/daemon/behavior.mjs +174 -0
- package/tools/daemon/concierge/intent-router.mjs +401 -0
- package/tools/daemon/concierge/orchestrator.mjs +272 -0
- package/tools/daemon/concierge/response-translator.mjs +462 -0
- package/tools/daemon/config.mjs +377 -0
- package/tools/daemon/cron-scheduler.mjs +178 -0
- package/tools/daemon/daemon-main.mjs +1169 -0
- package/tools/daemon/event-router.mjs +84 -0
- package/tools/daemon/file-watcher.mjs +383 -0
- package/tools/daemon/index.mjs +1181 -0
- package/tools/daemon/init-profile.mjs +124 -0
- package/tools/daemon/ipc-client.mjs +197 -0
- package/tools/daemon/ipc-ops-handlers.mjs +236 -0
- package/tools/daemon/ipc-server.mjs +275 -0
- package/tools/daemon/maintenance-owner.mjs +79 -0
- package/tools/daemon/memory-manager.mjs +386 -0
- package/tools/daemon/message-router.mjs +194 -0
- package/tools/daemon/provider-watcher.mjs +585 -0
- package/tools/daemon/pty-adapter.mjs +420 -0
- package/tools/daemon/repl-chat.mjs +359 -0
- package/tools/daemon/resource-bounds.mjs +88 -0
- package/tools/daemon/sandbox-transport.mjs +295 -0
- package/tools/daemon/scheduled-task-runner.mjs +535 -0
- package/tools/daemon/task-store.mjs +450 -0
- package/tools/daemon/tmux-manager.mjs +324 -0
- package/tools/daemon/update-policy.mjs +517 -0
- package/tools/daemon/web-server.mjs +399 -0
- package/tools/daemon/web-ui/index.html +585 -0
- package/tools/daemon/web-ui/styles.css +156 -0
- package/tools/docker/Dockerfile.daemon +35 -0
- package/tools/docker/container-manager.mjs +291 -0
- package/tools/messaging/adapter-registry.mjs +230 -0
- package/tools/messaging/adapters/base.mjs +326 -0
- package/tools/messaging/adapters/discord.mjs +462 -0
- package/tools/messaging/adapters/slack.mjs +402 -0
- package/tools/messaging/adapters/telegram.mjs +552 -0
- package/tools/messaging/chat-handler.mjs +297 -0
- package/tools/messaging/command-router.mjs +269 -0
- package/tools/messaging/event-bus.mjs +199 -0
- package/tools/messaging/index.mjs +456 -0
- package/tools/messaging/message-formatter.mjs +320 -0
- package/tools/messaging/room-manager.mjs +277 -0
- package/tools/messaging/types.mjs +94 -0
- package/tools/plugin/plugin-links.mjs +3 -0
- package/tools/providers/pi-bridge-policy.mjs +4 -0
- package/tools/ralph-external/daemon-supervisor.mjs +394 -0
- package/tools/ralph-external/lib/behavior-registry.mjs +270 -0
- package/tools/ralph-external/lib/worker-invocation-processes.mjs +3 -2
- package/tools/ralph-external/lib/worker-isolation-args.mjs +217 -0
- package/tools/ralph-external/lib/worker-isolation-status.mjs +19 -0
- package/tools/ralph-external/lib/worker-isolation.mjs +11 -237
- package/tools/ralph-external/lib/worker-overflow.mjs +10 -2
- package/tools/ralph-external/lib/worker-unit-cleanup.mjs +72 -0
- package/tools/ralph-external/session-launcher.mjs +7 -7
- package/tools/scripts/resource-preflight.mjs +3 -242
|
@@ -0,0 +1,517 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Opt-in update-install policy for the `update.install` maintenance job
|
|
3
|
+
* (epic #3353 slice B6; decision D3: installs are check-only by default).
|
|
4
|
+
*
|
|
5
|
+
* `update.check` stays check-only. `update.install` proceeds only when every
|
|
6
|
+
* gate passes, in order: explicit per-job opt-in (`args.install === true`),
|
|
7
|
+
* valid policy, maintenance window, available update, version policy (never a
|
|
8
|
+
* major unless explicitly allowed), no active AIWG work, and installer
|
|
9
|
+
* preflight (the installer's own dry-run checks). Any failed gate returns a
|
|
10
|
+
* `deferred` receipt with a machine-readable reason and never installs.
|
|
11
|
+
*
|
|
12
|
+
* Package install and provider redeployment are separate explicit steps: this
|
|
13
|
+
* module only performs the package step (`updateInstallation`) and never
|
|
14
|
+
* redeploys providers. An uncertain outcome (installer threw, receipt
|
|
15
|
+
* malformed) is reported with `uncertain: true` so the runner routes it to
|
|
16
|
+
* the existing `schedule-recovery-required` path instead of retrying it.
|
|
17
|
+
*/
|
|
18
|
+
|
|
19
|
+
import fs from 'node:fs';
|
|
20
|
+
import path from 'node:path';
|
|
21
|
+
import { importImpl } from '../_resolve-impl.mjs';
|
|
22
|
+
|
|
23
|
+
export const UPDATE_CHANNELS = Object.freeze(['stable', 'edge']);
|
|
24
|
+
export const VERSION_POLICIES = Object.freeze(['patch', 'minor', 'any']);
|
|
25
|
+
|
|
26
|
+
const TIME_RE = /^([01]\d|2[0-3]):([0-5]\d)$/;
|
|
27
|
+
const WEEKDAYS = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
|
|
28
|
+
const formatters = new Map();
|
|
29
|
+
|
|
30
|
+
function civilParts(ms, timezone) {
|
|
31
|
+
if (!formatters.has(timezone)) {
|
|
32
|
+
// Same named-zone civil-time approach as cron-scheduler.mjs: the Intl
|
|
33
|
+
// wall clock is the source of truth, so DST folds/gaps behave the same.
|
|
34
|
+
formatters.set(timezone, new Intl.DateTimeFormat('en-US', {
|
|
35
|
+
timeZone: timezone, weekday: 'short', hour: '2-digit', minute: '2-digit', hourCycle: 'h23',
|
|
36
|
+
}));
|
|
37
|
+
}
|
|
38
|
+
const parts = Object.fromEntries(formatters.get(timezone).formatToParts(ms).map(p => [p.type, p.value]));
|
|
39
|
+
return { weekday: WEEKDAYS.indexOf(parts.weekday), minutes: Number(parts.hour) * 60 + Number(parts.minute) };
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/**
|
|
43
|
+
* Validate the per-job update policy (`job.args` for `update.install`).
|
|
44
|
+
* Returns an array of human-readable errors; empty means valid.
|
|
45
|
+
*/
|
|
46
|
+
export function validateUpdatePolicy(args = {}) {
|
|
47
|
+
const errors = [];
|
|
48
|
+
if (args.channel !== undefined && !UPDATE_CHANNELS.includes(args.channel)) {
|
|
49
|
+
errors.push(`channel must be one of: ${UPDATE_CHANNELS.join(', ')}`);
|
|
50
|
+
}
|
|
51
|
+
if (args.versionPolicy !== undefined && !VERSION_POLICIES.includes(args.versionPolicy)) {
|
|
52
|
+
errors.push(`versionPolicy must be one of: ${VERSION_POLICIES.join(', ')}`);
|
|
53
|
+
}
|
|
54
|
+
if (args.allowMajor !== undefined && typeof args.allowMajor !== 'boolean') {
|
|
55
|
+
errors.push('allowMajor must be a boolean');
|
|
56
|
+
}
|
|
57
|
+
if (args.install !== undefined && typeof args.install !== 'boolean') {
|
|
58
|
+
errors.push('install must be a boolean');
|
|
59
|
+
}
|
|
60
|
+
if (args.windows !== undefined) {
|
|
61
|
+
if (!Array.isArray(args.windows) || args.windows.length === 0) {
|
|
62
|
+
errors.push('windows must be a non-empty array of { start, end, days?, timezone? }');
|
|
63
|
+
} else {
|
|
64
|
+
args.windows.forEach((window, index) => {
|
|
65
|
+
const label = `windows[${index}]`;
|
|
66
|
+
if (!window || typeof window !== 'object') { errors.push(`${label} must be an object`); return; }
|
|
67
|
+
for (const key of ['start', 'end']) {
|
|
68
|
+
if (typeof window[key] !== 'string' || !TIME_RE.test(window[key])) {
|
|
69
|
+
errors.push(`${label}.${key} must be HH:MM (24h)`);
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
if (window.days !== undefined) {
|
|
73
|
+
if (!Array.isArray(window.days) || window.days.length === 0 ||
|
|
74
|
+
window.days.some(d => !Number.isInteger(d) || d < 0 || d > 6)) {
|
|
75
|
+
errors.push(`${label}.days must be a non-empty array of 0 (Sun) through 6 (Sat)`);
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
if (window.timezone !== undefined) {
|
|
79
|
+
try { new Intl.DateTimeFormat('en', { timeZone: window.timezone }); }
|
|
80
|
+
catch { errors.push(`${label}.timezone is not a known IANA zone`); }
|
|
81
|
+
}
|
|
82
|
+
});
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
return errors;
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
function parseTriple(version) {
|
|
89
|
+
const match = /^(\d+)\.(\d+)\.(\d+)/.exec(String(version || ''));
|
|
90
|
+
return match ? [Number(match[1]), Number(match[2]), Number(match[3])] : null;
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/** Classify the bump from current to latest: none|patch|minor|major|unknown. */
|
|
94
|
+
export function classifyBump(current, latest) {
|
|
95
|
+
const from = parseTriple(current);
|
|
96
|
+
const to = parseTriple(latest);
|
|
97
|
+
if (!from || !to) return 'unknown';
|
|
98
|
+
if (to[0] !== from[0]) return 'major';
|
|
99
|
+
if (to[1] !== from[1]) return 'minor';
|
|
100
|
+
if (to[2] !== from[2]) return 'patch';
|
|
101
|
+
return 'none';
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
/** Version-policy gate: patch < minor < any; major always needs allowMajor. */
|
|
105
|
+
export function versionAllowed(current, latest, { versionPolicy = 'patch', allowMajor = false } = {}) {
|
|
106
|
+
const bump = classifyBump(current, latest);
|
|
107
|
+
if (bump === 'none' || bump === 'unknown') return { allowed: false, bump, reason: `no-${bump}-upgrade` };
|
|
108
|
+
if (bump === 'major' && !allowMajor) return { allowed: false, bump, reason: 'major-not-allowed' };
|
|
109
|
+
if (bump === 'major') return { allowed: true, bump, reason: 'major-explicitly-allowed' };
|
|
110
|
+
const rank = { patch: 0, minor: 1, any: 2 };
|
|
111
|
+
const ceiling = rank[versionPolicy] ?? 0;
|
|
112
|
+
if (rank[bump] <= ceiling) return { allowed: true, bump, reason: `within-${versionPolicy}-policy` };
|
|
113
|
+
return { allowed: false, bump, reason: 'version-policy' };
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
/**
|
|
117
|
+
* Maintenance-window gate. `windows` entries are
|
|
118
|
+
* `{ start: 'HH:MM', end: 'HH:MM', days?: [0-6 Sun-Sat], timezone? }`; ranges
|
|
119
|
+
* wrap past midnight. No windows configured means installs are allowed at any
|
|
120
|
+
* time (the `install: true` opt-in remains the safety gate).
|
|
121
|
+
*/
|
|
122
|
+
export function inMaintenanceWindow(nowMs, windows, fallbackTimezone = 'UTC') {
|
|
123
|
+
if (!windows || windows.length === 0) return { inside: true, reason: 'no-window-configured' };
|
|
124
|
+
for (const window of windows) {
|
|
125
|
+
const timezone = window.timezone || fallbackTimezone;
|
|
126
|
+
let parts;
|
|
127
|
+
try { parts = civilParts(nowMs, timezone); }
|
|
128
|
+
catch { continue; }
|
|
129
|
+
if (parts.weekday < 0) continue;
|
|
130
|
+
if (window.days && !window.days.includes(parts.weekday)) continue;
|
|
131
|
+
const [sh, sm] = window.start.split(':').map(Number);
|
|
132
|
+
const [eh, em] = window.end.split(':').map(Number);
|
|
133
|
+
const start = sh * 60 + sm;
|
|
134
|
+
const end = eh * 60 + em;
|
|
135
|
+
const inside = start <= end
|
|
136
|
+
? parts.minutes >= start && parts.minutes < end
|
|
137
|
+
: parts.minutes >= start || parts.minutes < end;
|
|
138
|
+
if (inside) return { inside: true, reason: `in-window:${window.start}-${window.end}@${timezone}` };
|
|
139
|
+
}
|
|
140
|
+
return { inside: false, reason: 'outside-maintenance-window' };
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
/**
|
|
144
|
+
* Read-only view of the daemon task store for active-work detection.
|
|
145
|
+
* Fail-closed: only a missing file (ENOENT) means "no daemon work". Any
|
|
146
|
+
* other read or parse error yields `unavailable`, which `detectActiveWork`
|
|
147
|
+
* turns into an active `work-detection-unavailable:<reason>` entry.
|
|
148
|
+
*/
|
|
149
|
+
export function readStoreWork(cwd) {
|
|
150
|
+
const file = path.join(cwd, '.aiwg', 'daemon', 'tasks.json');
|
|
151
|
+
let raw;
|
|
152
|
+
try {
|
|
153
|
+
raw = fs.readFileSync(file, 'utf8');
|
|
154
|
+
} catch (error) {
|
|
155
|
+
if (error?.code === 'ENOENT') return { busySchedules: [], busyTasks: [], unavailable: null };
|
|
156
|
+
return { busySchedules: [], busyTasks: [], unavailable: `work-detection-unavailable:${error.message}` };
|
|
157
|
+
}
|
|
158
|
+
try {
|
|
159
|
+
const parsed = JSON.parse(raw);
|
|
160
|
+
const schedules = Array.isArray(parsed.schedules) ? parsed.schedules : [];
|
|
161
|
+
const tasks = Array.isArray(parsed.tasks) ? parsed.tasks : [];
|
|
162
|
+
return {
|
|
163
|
+
busySchedules: schedules
|
|
164
|
+
.filter(s => ['running', 'blocked', 'retry', 'pending'].includes(s?.state))
|
|
165
|
+
.map(s => s?.job?.id || '?'),
|
|
166
|
+
busyTasks: tasks
|
|
167
|
+
.filter(t => ['running', 'queued'].includes(t?.state))
|
|
168
|
+
.map(t => t?.id || '?'),
|
|
169
|
+
unavailable: null,
|
|
170
|
+
};
|
|
171
|
+
} catch (error) {
|
|
172
|
+
return { busySchedules: [], busyTasks: [], unavailable: `work-detection-unavailable:${error.message}` };
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
/**
|
|
177
|
+
* Live ralph loops via the existing launcher registry reader
|
|
178
|
+
* (`getLoopStatuses` in `src/cli/handlers/ralph-launcher.ts`), which already
|
|
179
|
+
* folds process liveness into each entry. Falls back to reading the same
|
|
180
|
+
* registry file directly when the compiled reader is unavailable.
|
|
181
|
+
*/
|
|
182
|
+
export async function readActiveLoops(cwd) {
|
|
183
|
+
try {
|
|
184
|
+
const { getLoopStatuses } = await importImpl(import.meta.url, 'cli/handlers/ralph-launcher.js');
|
|
185
|
+
return getLoopStatuses(cwd)
|
|
186
|
+
.filter(entry => entry?.status === 'running')
|
|
187
|
+
.map(entry => entry?.loopId || '?');
|
|
188
|
+
} catch {
|
|
189
|
+
try {
|
|
190
|
+
const raw = fs.readFileSync(path.join(cwd, '.aiwg', 'ralph-external', 'launcher-registry.json'), 'utf8');
|
|
191
|
+
const loops = JSON.parse(raw).loops || {};
|
|
192
|
+
return Object.entries(loops)
|
|
193
|
+
.filter(([, entry]) => entry?.status === 'running' && isAlive(entry?.pid))
|
|
194
|
+
.map(([loopId]) => loopId);
|
|
195
|
+
} catch {
|
|
196
|
+
return [];
|
|
197
|
+
}
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
function isAlive(pid) {
|
|
202
|
+
if (!Number.isSafeInteger(pid) || pid <= 0) return false;
|
|
203
|
+
try { process.kill(pid, 0); return true; }
|
|
204
|
+
catch { return false; }
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
/**
|
|
208
|
+
* Direct-worker run directories known to AIWG launchers. There is no shared
|
|
209
|
+
* default `--runs-root`: every launcher records a per-worker `--run-dir`
|
|
210
|
+
* (Mission Control writes `<root>/.aiwg/ralph-external/mc/sessions/<session>/<mission>.run`;
|
|
211
|
+
* loop launches record `managedWorker.runDir` in the launcher registry).
|
|
212
|
+
* Missing roots mean "no workers"; any other discovery error throws so the
|
|
213
|
+
* caller fails closed.
|
|
214
|
+
*/
|
|
215
|
+
export function defaultWorkerRunDirs(cwd) {
|
|
216
|
+
const runDirs = [];
|
|
217
|
+
const sessionsDir = path.join(cwd, '.aiwg', 'ralph-external', 'mc', 'sessions');
|
|
218
|
+
let sessions;
|
|
219
|
+
try {
|
|
220
|
+
sessions = fs.readdirSync(sessionsDir, { withFileTypes: true });
|
|
221
|
+
} catch (error) {
|
|
222
|
+
if (error?.code !== 'ENOENT') throw error;
|
|
223
|
+
}
|
|
224
|
+
if (sessions) {
|
|
225
|
+
for (const session of sessions) {
|
|
226
|
+
if (!session.isDirectory()) continue;
|
|
227
|
+
let children;
|
|
228
|
+
try {
|
|
229
|
+
children = fs.readdirSync(path.join(sessionsDir, session.name), { withFileTypes: true });
|
|
230
|
+
} catch (error) {
|
|
231
|
+
if (error?.code === 'ENOENT') continue;
|
|
232
|
+
throw error;
|
|
233
|
+
}
|
|
234
|
+
for (const child of children) {
|
|
235
|
+
if (child.isDirectory() && child.name.endsWith('.run')) {
|
|
236
|
+
runDirs.push(path.join(sessionsDir, session.name, child.name));
|
|
237
|
+
}
|
|
238
|
+
}
|
|
239
|
+
}
|
|
240
|
+
}
|
|
241
|
+
const registryFile = path.join(cwd, '.aiwg', 'ralph-external', 'launcher-registry.json');
|
|
242
|
+
let registryRaw;
|
|
243
|
+
try {
|
|
244
|
+
registryRaw = fs.readFileSync(registryFile, 'utf8');
|
|
245
|
+
} catch (error) {
|
|
246
|
+
if (error?.code !== 'ENOENT') throw error;
|
|
247
|
+
}
|
|
248
|
+
if (registryRaw !== undefined) {
|
|
249
|
+
const loops = JSON.parse(registryRaw).loops || {};
|
|
250
|
+
for (const entry of Object.values(loops)) {
|
|
251
|
+
if (typeof entry?.managedWorker?.runDir === 'string' && entry.managedWorker.runDir) {
|
|
252
|
+
runDirs.push(path.resolve(cwd, entry.managedWorker.runDir));
|
|
253
|
+
}
|
|
254
|
+
}
|
|
255
|
+
}
|
|
256
|
+
return [...new Set(runDirs)];
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
/** Default `sampleWorkerStatus` entry point (same reader `aiwg ralph-external --status --workers` uses). */
|
|
260
|
+
async function defaultSampleWorker({ runDir }) {
|
|
261
|
+
const { sampleWorkerStatus } = await import('../ralph-external/process-monitor.mjs');
|
|
262
|
+
return sampleWorkerStatus({ runDir });
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
/**
|
|
266
|
+
* Live direct workers via the existing `sampleWorkerStatus` reader. Any
|
|
267
|
+
* worker row whose `terminal` flag is not true (launching/started/active/
|
|
268
|
+
* quiet/stalled/hung, plus unreadable rows) counts as active work.
|
|
269
|
+
* An incomplete sample or a sampler failure throws `work-detection-unavailable`
|
|
270
|
+
* so the caller fails closed. `runDirs`/`sample` are injectable; production
|
|
271
|
+
* passes absolute run dirs discovered by `defaultWorkerRunDirs`.
|
|
272
|
+
*/
|
|
273
|
+
export async function readActiveWorkers(cwd, { runDirs = null, sample = null } = {}) {
|
|
274
|
+
const dirs = runDirs ?? defaultWorkerRunDirs(cwd);
|
|
275
|
+
const sampler = sample ?? defaultSampleWorker;
|
|
276
|
+
const active = [];
|
|
277
|
+
for (const runDir of dirs) {
|
|
278
|
+
let report;
|
|
279
|
+
try {
|
|
280
|
+
report = await sampler({ runDir });
|
|
281
|
+
} catch (error) {
|
|
282
|
+
throw new Error(`work-detection-unavailable:${error.message}`);
|
|
283
|
+
}
|
|
284
|
+
for (const row of report?.workers || []) {
|
|
285
|
+
if (row?.terminal !== true) active.push(`direct-worker:${row?.invocationId || '?'}`);
|
|
286
|
+
}
|
|
287
|
+
if (!report || report.complete !== true) {
|
|
288
|
+
const hint = report?.findings?.[0] || 'incomplete-sample';
|
|
289
|
+
throw new Error(`work-detection-unavailable:${hint}`);
|
|
290
|
+
}
|
|
291
|
+
}
|
|
292
|
+
return active;
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
/** Mission statuses that no longer block an install (`MissionStatus` in `src/cli/handlers/mc.ts`). */
|
|
296
|
+
const MISSION_TERMINAL_STATUSES = new Set(['done', 'failed', 'aborted']);
|
|
297
|
+
|
|
298
|
+
/**
|
|
299
|
+
* Non-terminal Mission Control missions. There is no exported reusable
|
|
300
|
+
* mission reader (`readSession`/`listSessions` are private to
|
|
301
|
+
* `src/cli/handlers/mc.ts`, behind `aiwg mc status/list`), so this reads the
|
|
302
|
+
* same store those commands read — `.aiwg/ralph-external/mc/sessions/*\/session.json`
|
|
303
|
+
* — directly, mirroring the launcher-registry fallback in `readActiveLoops`.
|
|
304
|
+
* Queued, running, and paused missions all block: a paused mission still
|
|
305
|
+
* holds reservations and resumes. A missing sessions root means "no
|
|
306
|
+
* missions"; any other read or parse error throws so the caller fails
|
|
307
|
+
* closed.
|
|
308
|
+
*/
|
|
309
|
+
export function readActiveMissions(cwd) {
|
|
310
|
+
const sessionsDir = path.join(cwd, '.aiwg', 'ralph-external', 'mc', 'sessions');
|
|
311
|
+
let sessions;
|
|
312
|
+
try {
|
|
313
|
+
sessions = fs.readdirSync(sessionsDir, { withFileTypes: true });
|
|
314
|
+
} catch (error) {
|
|
315
|
+
if (error?.code === 'ENOENT') return [];
|
|
316
|
+
throw new Error(`work-detection-unavailable:${error.message}`);
|
|
317
|
+
}
|
|
318
|
+
const active = [];
|
|
319
|
+
for (const session of sessions) {
|
|
320
|
+
if (!session.isDirectory()) continue;
|
|
321
|
+
const file = path.join(sessionsDir, session.name, 'session.json');
|
|
322
|
+
let raw;
|
|
323
|
+
try {
|
|
324
|
+
raw = fs.readFileSync(file, 'utf8');
|
|
325
|
+
} catch (error) {
|
|
326
|
+
if (error?.code === 'ENOENT') continue;
|
|
327
|
+
throw new Error(`work-detection-unavailable:${error.message}`);
|
|
328
|
+
}
|
|
329
|
+
let parsed;
|
|
330
|
+
try {
|
|
331
|
+
parsed = JSON.parse(raw);
|
|
332
|
+
} catch (error) {
|
|
333
|
+
throw new Error(`work-detection-unavailable:${error.message}`);
|
|
334
|
+
}
|
|
335
|
+
for (const mission of Array.isArray(parsed?.missions) ? parsed.missions : []) {
|
|
336
|
+
if (!MISSION_TERMINAL_STATUSES.has(mission?.status)) active.push(`mission:${mission?.id || '?'}`);
|
|
337
|
+
}
|
|
338
|
+
}
|
|
339
|
+
return active;
|
|
340
|
+
}
|
|
341
|
+
|
|
342
|
+
/**
|
|
343
|
+
* Active-work gate. Reuses the existing detectors only: daemon task-store
|
|
344
|
+
* schedules/agent tasks, ralph loop liveness, direct-worker status, and
|
|
345
|
+
* Mission Control missions. Returns `{ active, reasons }`. Every reader
|
|
346
|
+
* failure (other than "store/reader simply absent") reports
|
|
347
|
+
* `active: true` with a `work-detection-unavailable:<reason>` entry.
|
|
348
|
+
*/
|
|
349
|
+
export async function detectActiveWork({ cwd = process.cwd(), taskStore = null, readLoops = readActiveLoops, readWorkers = readActiveWorkers, readMissions = readActiveMissions } = {}) {
|
|
350
|
+
const reasons = [];
|
|
351
|
+
const store = taskStore
|
|
352
|
+
? {
|
|
353
|
+
busySchedules: (taskStore.getSchedules?.() || [])
|
|
354
|
+
.filter(s => ['running', 'blocked', 'retry', 'pending'].includes(s?.state))
|
|
355
|
+
.map(s => s?.job?.id || '?'),
|
|
356
|
+
busyTasks: (taskStore.getTasks?.() || [])
|
|
357
|
+
.filter(t => ['running', 'queued'].includes(t?.state))
|
|
358
|
+
.map(t => t?.id || '?'),
|
|
359
|
+
unavailable: null,
|
|
360
|
+
}
|
|
361
|
+
: readStoreWork(cwd);
|
|
362
|
+
for (const id of store.busySchedules) reasons.push(`daemon-task:${id}`);
|
|
363
|
+
for (const id of store.busyTasks) reasons.push(`agent-task:${id}`);
|
|
364
|
+
if (store.unavailable) reasons.push(store.unavailable);
|
|
365
|
+
for (const [reader, prefix] of [[readLoops, 'ralph-loop:'], [readWorkers, ''], [readMissions, '']]) {
|
|
366
|
+
try {
|
|
367
|
+
const ids = await reader(cwd);
|
|
368
|
+
for (const id of ids || []) reasons.push(prefix ? `${prefix}${id}` : id);
|
|
369
|
+
} catch (error) {
|
|
370
|
+
const reason = String(error?.message || error);
|
|
371
|
+
reasons.push(reason.startsWith('work-detection-unavailable:') ? reason : `work-detection-unavailable:${reason}`);
|
|
372
|
+
return { active: true, reasons };
|
|
373
|
+
}
|
|
374
|
+
}
|
|
375
|
+
return { active: reasons.length > 0, reasons };
|
|
376
|
+
}
|
|
377
|
+
|
|
378
|
+
// Injectable seams for tests. Production always uses the lazy defaults, which
|
|
379
|
+
// resolve the checker's check-only probe and the installer's own preflight and
|
|
380
|
+
// install entry points — never a copy of their logic.
|
|
381
|
+
const testSeams = {};
|
|
382
|
+
export function setUpdateInstallSeams(seams) { Object.assign(testSeams, seams); }
|
|
383
|
+
export function resetUpdateInstallSeams() { for (const key of Object.keys(testSeams)) delete testSeams[key]; }
|
|
384
|
+
|
|
385
|
+
/**
|
|
386
|
+
* Resolve the owner entry points, loading the real checker/installer only for
|
|
387
|
+
* keys the caller did not inject. Tests inject every seam, so they never
|
|
388
|
+
* perform a probe or install and never need a built dist/.
|
|
389
|
+
*/
|
|
390
|
+
async function resolveDeps(overrides = {}) {
|
|
391
|
+
const merged = { now: Date.now, detectActiveWork, ...testSeams, ...overrides };
|
|
392
|
+
if (!merged.checkUpdateStatus || !merged.detectInstallMode || !merged.dryRunInstall || !merged.performInstall) {
|
|
393
|
+
const [{ checkUpdateStatus }, service] = await Promise.all([
|
|
394
|
+
importImpl(import.meta.url, 'update/checker.mjs'),
|
|
395
|
+
importImpl(import.meta.url, 'update/service.mjs'),
|
|
396
|
+
]);
|
|
397
|
+
merged.checkUpdateStatus ??= checkUpdateStatus;
|
|
398
|
+
merged.detectInstallMode ??= service.detectInstallMode;
|
|
399
|
+
merged.dryRunInstall ??= options => service.updateInstallation({ ...options, dryRun: true });
|
|
400
|
+
merged.performInstall ??= options => service.updateInstallation(options);
|
|
401
|
+
}
|
|
402
|
+
return merged;
|
|
403
|
+
}
|
|
404
|
+
|
|
405
|
+
function deferred(reason, summary, detail) {
|
|
406
|
+
return { exitStatus: 2, state: 'deferred', reason, summary, detail };
|
|
407
|
+
}
|
|
408
|
+
|
|
409
|
+
/**
|
|
410
|
+
* Run one `update.install` job through every gate. Returns an owner receipt:
|
|
411
|
+
* `{ exitStatus, state?, reason?, summary, detail?, uncertain? }`.
|
|
412
|
+
*/
|
|
413
|
+
export async function runUpdateInstall(job, overrides = {}) {
|
|
414
|
+
const args = job?.args || {};
|
|
415
|
+
const channel = args.channel || 'stable';
|
|
416
|
+
|
|
417
|
+
// These gates need no owner entry points, so refusals never load them.
|
|
418
|
+
if (args.install !== true) {
|
|
419
|
+
return deferred('install-not-enabled',
|
|
420
|
+
'Refusing update.install: installs are check-only by default (decision D3); enable per job with args.install: true',
|
|
421
|
+
{ channel, checkOnly: true });
|
|
422
|
+
}
|
|
423
|
+
const policyErrors = validateUpdatePolicy(args);
|
|
424
|
+
if (policyErrors.length > 0) {
|
|
425
|
+
return deferred('invalid-policy', `Refusing update.install: ${policyErrors.join('; ')}`, { channel });
|
|
426
|
+
}
|
|
427
|
+
const clock = overrides.now || testSeams.now || Date.now;
|
|
428
|
+
const window = inMaintenanceWindow(clock(), args.windows, job.timezone || 'UTC');
|
|
429
|
+
if (!window.inside) {
|
|
430
|
+
return deferred('outside-maintenance-window',
|
|
431
|
+
`Refusing update.install: ${window.reason}; no install is attempted outside a maintenance window`,
|
|
432
|
+
{ channel, window: window.reason });
|
|
433
|
+
}
|
|
434
|
+
const configured = await resolveDeps(overrides);
|
|
435
|
+
|
|
436
|
+
let status;
|
|
437
|
+
try {
|
|
438
|
+
status = await configured.checkUpdateStatus({ channel });
|
|
439
|
+
} catch (error) {
|
|
440
|
+
return { exitStatus: null, uncertain: true, summary: `Update probe failed; inspect before recovery: ${error.message}` };
|
|
441
|
+
}
|
|
442
|
+
if (!status || status.status === 'unsupported') {
|
|
443
|
+
return deferred('unsupported-channel',
|
|
444
|
+
`Deferring update.install: channel '${channel}' has no read-only probe; edge installs stay manual`,
|
|
445
|
+
{ channel, checkOnly: true });
|
|
446
|
+
}
|
|
447
|
+
if (!status.available) {
|
|
448
|
+
return { exitStatus: 0, summary: `Already current on ${channel} (${status.current})`,
|
|
449
|
+
detail: { ...status, rollback: null, redeploy: 'not-performed' } };
|
|
450
|
+
}
|
|
451
|
+
const gate = versionAllowed(status.current, status.latest, args);
|
|
452
|
+
if (!gate.allowed) {
|
|
453
|
+
return deferred(gate.reason,
|
|
454
|
+
`Refusing update.install ${status.current} → ${status.latest} (${gate.bump}): ${gate.reason}; adjust versionPolicy/allowMajor explicitly to proceed`,
|
|
455
|
+
{ ...status, bump: gate.bump });
|
|
456
|
+
}
|
|
457
|
+
|
|
458
|
+
const work = await configured.detectActiveWork({ cwd: overrides.cwd || process.cwd() });
|
|
459
|
+
if (work.active) {
|
|
460
|
+
return deferred('active-work',
|
|
461
|
+
`Deferring update.install: active AIWG work detected (${work.reasons.join(', ')}); installs never run alongside live work`,
|
|
462
|
+
{ ...status, activeWork: work.reasons });
|
|
463
|
+
}
|
|
464
|
+
|
|
465
|
+
let preflight;
|
|
466
|
+
try {
|
|
467
|
+
preflight = await configured.dryRunInstall({ channel });
|
|
468
|
+
} catch (error) {
|
|
469
|
+
return deferred('preflight-failed',
|
|
470
|
+
`Refusing update.install: installer preflight failed: ${error.message}`,
|
|
471
|
+
{ ...status });
|
|
472
|
+
}
|
|
473
|
+
if (preflight?.status === 'manual') {
|
|
474
|
+
return deferred('install-manual-required',
|
|
475
|
+
`Deferring update.install: ${preflight.message}`,
|
|
476
|
+
{ ...status, installMode: preflight.mode });
|
|
477
|
+
}
|
|
478
|
+
if (preflight?.status === 'unsupported-offline') {
|
|
479
|
+
return deferred('preflight-failed',
|
|
480
|
+
`Deferring update.install: installer is offline: ${preflight.message}`,
|
|
481
|
+
{ ...status });
|
|
482
|
+
}
|
|
483
|
+
|
|
484
|
+
let result;
|
|
485
|
+
try {
|
|
486
|
+
result = await configured.performInstall({ channel });
|
|
487
|
+
} catch (error) {
|
|
488
|
+
// The installer threw mid-flight: effects are unknown, so this goes to
|
|
489
|
+
// the schedule-recovery-required path and is never auto-retried.
|
|
490
|
+
return { exitStatus: null, uncertain: true,
|
|
491
|
+
summary: `Update install outcome uncertain; inspect effects before recovery: ${error.message}`,
|
|
492
|
+
detail: { ...status, attemptedInstall: true } };
|
|
493
|
+
}
|
|
494
|
+
if (!result || typeof result !== 'object' || (result.changed !== true && result.status !== 'updated')) {
|
|
495
|
+
return { exitStatus: null, uncertain: true,
|
|
496
|
+
summary: 'Update install returned an unrecognized receipt; inspect effects before recovery',
|
|
497
|
+
detail: { ...status, installerResult: result || null } };
|
|
498
|
+
}
|
|
499
|
+
const rollback = rollbackGuidance(result, status);
|
|
500
|
+
return { exitStatus: 0,
|
|
501
|
+
summary: `Updated ${status.current} → ${result.version || status.latest} on ${channel}; provider redeploy NOT performed`,
|
|
502
|
+
detail: { ...status, oldVersion: status.current, newVersion: result.version || status.latest,
|
|
503
|
+
installMode: result.mode, rollback, redeploy: 'not-performed',
|
|
504
|
+
redeployHint: 'Re-deploy providers separately when ready: aiwg update --skip-check' } };
|
|
505
|
+
}
|
|
506
|
+
|
|
507
|
+
function rollbackGuidance(result, status) {
|
|
508
|
+
if (result.mode === 'npm' && result.command) {
|
|
509
|
+
const manager = result.command.split(' ')[0];
|
|
510
|
+
return { how: `Re-install the previous version: ${manager} install --global aiwg@${status.current}`,
|
|
511
|
+
command: `${manager} install --global aiwg@${status.current}` };
|
|
512
|
+
}
|
|
513
|
+
if (result.mode === 'web') {
|
|
514
|
+
return { how: 'Re-resolve the previous signed web resource release for this channel; verified cached resources remain available offline.' };
|
|
515
|
+
}
|
|
516
|
+
return { how: 'Manual installation: restore the previous checkout or package from your own backup before re-running.' };
|
|
517
|
+
}
|