@aiwg/cli 2026.10.15 → 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/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 +8 -3
- package/dist/src/artifacts/corpus-tools/discovery-log.js +26 -24
- package/dist/src/artifacts/corpus-tools/expand-cli.js +3 -2
- package/dist/src/artifacts/corpus-tools/expand-dates.js +107 -0
- package/dist/src/artifacts/corpus-tools/expand-queue.js +4 -1
- package/dist/src/artifacts/corpus-tools/expand-review.js +104 -0
- package/dist/src/artifacts/corpus-tools/expand-state.js +17 -1
- package/dist/src/artifacts/corpus-tools/expand.js +16 -17
- 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 +11 -3
- package/dist/src/artifacts/corpus-tools/resolve.js +23 -9
- 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 +10 -5
- package/dist/src/cli/handlers/doctor-help.js +4 -1
- 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 -560
- 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-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 +8 -1
- 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/gates/heldout.js +17 -7
- 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-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 +4 -30
- package/dist/src/research/clients/base.js +48 -22
- package/dist/src/research/identity.js +34 -2
- 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 +70 -24
- 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/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/aiwg-md.js +16 -46
- 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 +9 -10
- package/dist/src/smiths/context-pipeline/managed-hook.js +1 -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 +10 -1
- package/schemas/decision/D29Study.v10.schema.json +65 -0
- package/tools/agents/deploy-agents.mjs +10 -0
- package/tools/agents/providers/claude-post-deploy.mjs +12 -1
- package/tools/agents/providers/context-write.mjs +4 -0
- package/tools/agents/providers/pi.mjs +3 -1
- package/tools/agents/providers/rule-delivery-surface.mjs +332 -0
- package/tools/agents/providers/rule-delivery.mjs +20 -1144
- 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/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/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,332 @@
|
|
|
1
|
+
// Select and project deployment rules and measure startup context.
|
|
2
|
+
import { createHash } from 'node:crypto';
|
|
3
|
+
import fs from 'node:fs';
|
|
4
|
+
import path from 'node:path';
|
|
5
|
+
import { importImpl } from '../../_resolve-impl.mjs';
|
|
6
|
+
import {
|
|
7
|
+
addManagedMarker,
|
|
8
|
+
contentHash,
|
|
9
|
+
getFrameworksForMode,
|
|
10
|
+
listMdFiles,
|
|
11
|
+
replaceBoundRulesBlock,
|
|
12
|
+
resolveAiwgRoot,
|
|
13
|
+
ruleEnforcementLevel,
|
|
14
|
+
} from './base.mjs';
|
|
15
|
+
import { resolveDeliveryRuleBindings } from './rule-binding-targets.mjs';
|
|
16
|
+
import { inlineStartup, nativePathLoader, ruleDirectory } from './rule-projection.mjs';
|
|
17
|
+
|
|
18
|
+
export const { parseRuleFrontmatter, inferRuleActivation, readCoreBody, validateCoreSet, formatRuleFrontmatterError } = await importImpl(import.meta.url, 'rules/activation.mjs');
|
|
19
|
+
export const { resolveDeployVersion } = await importImpl(import.meta.url, 'providers/deploy-version.mjs');
|
|
20
|
+
export const { trackTemporaryDirectory } = await importImpl(import.meta.url, 'utils/temporary-directory.js');
|
|
21
|
+
export const { loadRulePinConfigs, installedRuleCapabilities, resolveRulePins } = await importImpl(import.meta.url, 'rules/pins.mjs');
|
|
22
|
+
export const { guardRulesInlineBudget } = await importImpl(import.meta.url, 'rules/inline-budget.mjs');
|
|
23
|
+
export const { userConfigFile } = await importImpl(import.meta.url, 'config/user-config-dir.mjs');
|
|
24
|
+
export const { resolveProjectAiwgDir } = await importImpl(import.meta.url, 'config/project-artifacts-runtime.mjs');
|
|
25
|
+
export { renderRuleKernelIndex } from './rule-presentation.mjs';
|
|
26
|
+
export const PREPARATION_HOOK = Symbol.for('aiwg.provider-preparation-hook.v1');
|
|
27
|
+
|
|
28
|
+
export function installRuleDeploymentPreparationHook(hook) {
|
|
29
|
+
if (!hook || typeof hook.scratch !== 'string' || !hook.inputPool || typeof hook.accept !== 'function' || globalThis[PREPARATION_HOOK]) {
|
|
30
|
+
throw new Error('Invalid or already active rule deployment preparation hook');
|
|
31
|
+
}
|
|
32
|
+
globalThis[PREPARATION_HOOK] = hook;
|
|
33
|
+
return () => { if (globalThis[PREPARATION_HOOK] === hook) delete globalThis[PREPARATION_HOOK]; };
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
export function isRuleDeploymentPreparationActive() {
|
|
37
|
+
return Boolean(globalThis[PREPARATION_HOOK]);
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
export function walk(dir) {
|
|
41
|
+
if (!fs.existsSync(dir)) return [];
|
|
42
|
+
return fs.readdirSync(dir, { withFileTypes: true }).flatMap(entry => {
|
|
43
|
+
const file = path.join(dir, entry.name);
|
|
44
|
+
return entry.isDirectory() ? walk(file) : entry.isFile() ? [file] : [];
|
|
45
|
+
});
|
|
46
|
+
}
|
|
47
|
+
// Keep only digests in the transaction snapshot. Artifact stores and binary skill
|
|
48
|
+
// resources can be much larger than the provider output being changed.
|
|
49
|
+
export function fileDigest(file) {
|
|
50
|
+
const hash = createHash('sha256');
|
|
51
|
+
const buffer = Buffer.allocUnsafe(64 * 1024);
|
|
52
|
+
const fd = fs.openSync(file, 'r');
|
|
53
|
+
try {
|
|
54
|
+
let count;
|
|
55
|
+
while ((count = fs.readSync(fd, buffer, 0, buffer.length, null))) hash.update(buffer.subarray(0, count));
|
|
56
|
+
return hash.digest('hex');
|
|
57
|
+
} finally {
|
|
58
|
+
fs.closeSync(fd);
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
// Empty directories are part of workspace and skill-resource scaffolds too.
|
|
62
|
+
export function promoteDirectories(source, destination, skip = () => false, prefix = '') {
|
|
63
|
+
const entries = fs.readdirSync(source, { withFileTypes: true });
|
|
64
|
+
if (!entries.length && !fs.existsSync(destination)) fs.mkdirSync(destination, { recursive: true });
|
|
65
|
+
for (const entry of entries) {
|
|
66
|
+
const rel = path.join(prefix, entry.name);
|
|
67
|
+
if (entry.isDirectory() && !skip(rel)) {
|
|
68
|
+
promoteDirectories(path.join(source, entry.name), path.join(destination, entry.name), skip, rel);
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
export const read = file => fs.existsSync(file) ? fs.readFileSync(file, 'utf8') : '';
|
|
73
|
+
export const structural = file => /^(RULES-INDEX|RULES-ONDEMAND)\.(md|mdc)$/.test(path.basename(file));
|
|
74
|
+
/** Collect selected source contracts, before any tier filter or projection. */
|
|
75
|
+
export function collectDeploymentRuleSources(opts) {
|
|
76
|
+
if (opts.ruleSources) {
|
|
77
|
+
// Pin-only callers enumerate rule files separately from behavior contracts.
|
|
78
|
+
// Retain earlier behaviors only while their owning bundle is still selected.
|
|
79
|
+
const selected = new Set(collectDeploymentRuleSources({ ...opts, ruleSources: undefined }));
|
|
80
|
+
const behaviors = (opts.previousRuleSources || []).filter(file => path.basename(file) === 'BEHAVIOR.md' && selected.has(file));
|
|
81
|
+
return [...new Set([...opts.ruleSources, ...behaviors])];
|
|
82
|
+
}
|
|
83
|
+
const corpus = resolveAiwgRoot(opts.srcRoot) || opts.srcRoot;
|
|
84
|
+
const bundles = [];
|
|
85
|
+
const frameworks = getFrameworksForMode(corpus, 'all');
|
|
86
|
+
for (const kind of ['frameworks', 'addons', 'extensions', 'plugins']) {
|
|
87
|
+
const dir = path.join(corpus, 'agentic', 'code', kind);
|
|
88
|
+
if (!fs.existsSync(dir)) continue;
|
|
89
|
+
for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
|
|
90
|
+
if (!entry.isDirectory()) continue;
|
|
91
|
+
const root = path.join(dir, entry.name);
|
|
92
|
+
const manifest = JSON.parse(read(path.join(root, 'manifest.json')) || '{}');
|
|
93
|
+
bundles.push({ root, manifest, id: manifest.id || manifest.framework || entry.name,
|
|
94
|
+
aliases: [entry.name, ...(manifest.modeAliases || []), ...(manifest.aliases || []),
|
|
95
|
+
...(kind === 'frameworks' ? frameworks.find(framework => framework.path === root)?.aliases || [] : [])] });
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
const configs = opts.pinConfigs || loadRulePinConfigs(opts.target, opts.config);
|
|
99
|
+
// Project installation is authoritative. User-wide discoverability is not a
|
|
100
|
+
// project install, and a previous projection must never reselect retired rules.
|
|
101
|
+
const installed = configs.project.installed || {};
|
|
102
|
+
const names = Array.isArray(installed) ? installed : Object.keys(installed);
|
|
103
|
+
const selected = new Set();
|
|
104
|
+
const select = name => {
|
|
105
|
+
const id = name.replace(/^(framework|addon|extension|plugin):/, '');
|
|
106
|
+
const bundle = bundles.find(b => b.id === id || b.aliases.includes(id));
|
|
107
|
+
if (!bundle || selected.has(bundle)) return;
|
|
108
|
+
selected.add(bundle);
|
|
109
|
+
const required = Array.isArray(bundle.manifest.dependencies) ? bundle.manifest.dependencies : bundle.manifest.dependencies?.required || [];
|
|
110
|
+
for (const dep of Array.isArray(required) ? required : Object.keys(required)) select(dep);
|
|
111
|
+
};
|
|
112
|
+
for (const bundle of bundles.filter(b => b.manifest.core && b.manifest.autoInstall)) select(bundle.id);
|
|
113
|
+
for (const name of names.filter(name => name !== 'all')) select(name);
|
|
114
|
+
const invoked = bundles.find(bundle => path.resolve(bundle.root) === path.resolve(opts.srcRoot));
|
|
115
|
+
if (invoked && !opts.kernelOnly) select(invoked.id);
|
|
116
|
+
// Include the invocation being installed before its config entry is saved.
|
|
117
|
+
if (!opts.kernelOnly) for (const framework of getFrameworksForMode(opts.srcRoot, opts.mode === 'all' && names.length ? 'general' : opts.mode)) select(framework.id);
|
|
118
|
+
const roots = [...(!invoked || !opts.kernelOnly ? [opts.srcRoot] : []), ...(opts.additionalSources || []), ...[...selected].map(bundle => bundle.root)];
|
|
119
|
+
for (const entry of Object.values(installed)) if (entry?.localPath) roots.push(path.resolve(opts.target, entry.localPath));
|
|
120
|
+
const files = roots.flatMap(root => listMdFiles(path.join(root, 'rules'))).filter(file => !structural(file));
|
|
121
|
+
const behaviors = roots.flatMap(root => walk(path.join(root, 'behaviors')).filter(file => path.basename(file) === 'BEHAVIOR.md'));
|
|
122
|
+
return [...new Set([...files, ...behaviors])];
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
export async function prepareRuleDelivery(opts) {
|
|
126
|
+
const rules = collectDeploymentRuleSources(opts).map(file => {
|
|
127
|
+
const content = fs.readFileSync(file, 'utf8');
|
|
128
|
+
const parsed = parseRuleFrontmatter(content);
|
|
129
|
+
if (!parsed.valid) throw new Error(formatRuleFrontmatterError(opts.logicalInputPath ? opts.logicalInputPath(file) : file, parsed.data, parsed.diagnostics));
|
|
130
|
+
const behavior = path.basename(file) === 'BEHAVIOR.md';
|
|
131
|
+
const rule = { ...parsed.rule, file, content, body: parsed.body, behavior,
|
|
132
|
+
name: behavior ? `behavior/${path.basename(path.dirname(file))}` : parsed.data.name || path.basename(file, '.md') };
|
|
133
|
+
if (!rule.tagged) rule.activation = inferRuleActivation();
|
|
134
|
+
// Core rules (#3450) carry a compact body beside the full rule; the full text is never inlined.
|
|
135
|
+
if (rule.activation === 'core') rule.coreBody = readCoreBody(file);
|
|
136
|
+
for (const diagnostic of parsed.diagnostics) {
|
|
137
|
+
console.warn(`${opts.logicalInputPath ? opts.logicalInputPath(file) : file}: ${diagnostic.code}: ${diagnostic.code === 'missing-activation' ? `Missing activation; inferred ${rule.activation} delivery (migration fallback); add explicit activation frontmatter.` : diagnostic.message}`);
|
|
138
|
+
}
|
|
139
|
+
return rule;
|
|
140
|
+
});
|
|
141
|
+
const coreErrors = validateCoreSet([...new Map(rules.filter(rule => rule.coreBody !== undefined).map(rule => [rule.name, { name: rule.name, text: rule.coreBody }])).values()]);
|
|
142
|
+
if (coreErrors.length) throw new Error(coreErrors.join('; '));
|
|
143
|
+
const configs = opts.pinConfigs || loadRulePinConfigs(opts.target, opts.config);
|
|
144
|
+
const installed = installedRuleCapabilities(configs);
|
|
145
|
+
const root = resolveAiwgRoot(opts.srcRoot) || opts.srcRoot;
|
|
146
|
+
const { loadRelations, selectPrebuiltRelations } = await importImpl(import.meta.url, 'artifacts/relations.js');
|
|
147
|
+
const packageRelations = selectPrebuiltRelations(root, opts.target).reader;
|
|
148
|
+
const relations = packageRelations || loadRelations(opts.target) || loadRelations(root, opts.target);
|
|
149
|
+
const ruleIdsByPath = new Map(Object.entries(relations?.index.rules || {}).map(([id, rule]) => [rule.path, id]));
|
|
150
|
+
const pinRules = rules.map(rule => {
|
|
151
|
+
const owner = rule.file.replaceAll('\\', '/').match(/(?:frameworks|addons|extensions|plugins)\/([^/]+)\//)?.[1];
|
|
152
|
+
const local = Object.entries(configs.project.installed || {}).find(([, entry]) => entry.localPath && rule.file.startsWith(path.resolve(opts.target, entry.localPath) + path.sep))?.[0];
|
|
153
|
+
const indexedPath = path.relative(root, rule.file);
|
|
154
|
+
return { ...rule, id: ruleIdsByPath.get(indexedPath) || rule.file, path: rule.file, indexedPath,
|
|
155
|
+
capability: local || owner || opts.capability, enforcement: ruleEnforcementLevel(rule.content) };
|
|
156
|
+
});
|
|
157
|
+
const pinned = resolveRulePins({ rules: pinRules, configs, installed, relations });
|
|
158
|
+
for (const warning of pinned.warnings) console.warn(warning);
|
|
159
|
+
const pinsByFile = new Map(pinned.rules.map(rule => [rule.file, rule]));
|
|
160
|
+
for (const rule of rules) {
|
|
161
|
+
const pin = pinsByFile.get(rule.file);
|
|
162
|
+
// A core rule is already delivered in full; a pin must not re-promote it to a kernel body.
|
|
163
|
+
if (!pin || rule.activation === 'core') continue;
|
|
164
|
+
rule.canonicalActivation = rule.activation;
|
|
165
|
+
rule.pinMatches = pin.matches;
|
|
166
|
+
rule.pinned = true;
|
|
167
|
+
rule.activation = 'kernel';
|
|
168
|
+
// All pins use native kernel projection, including legacy untagged rules.
|
|
169
|
+
rule.tagged = true;
|
|
170
|
+
}
|
|
171
|
+
const { bindings, targets } = await resolveDeliveryRuleBindings(opts, rules, configs, root, packageRelations);
|
|
172
|
+
return { rules, bindings, targets, pins: pinned.rules, pinWarnings: pinned.warnings };
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
export const managed = (content, opts) => addManagedMarker(content, opts.deployVersion, opts.deploySource || 'bundled');
|
|
176
|
+
export function put(file, content) { fs.mkdirSync(path.dirname(file), { recursive: true }); fs.writeFileSync(file, content); }
|
|
177
|
+
|
|
178
|
+
/** External helpers also project skills/flows. Inject into their body, never descriptions. */
|
|
179
|
+
export function finishBindings(opts, provider) {
|
|
180
|
+
const roots = [opts.target, opts.deploymentHome,
|
|
181
|
+
...[opts.kernelSkillsPath, opts.activeWorkspace, ...Object.values(provider.paths)].filter(p => p && path.isAbsolute(p))];
|
|
182
|
+
const files = [...new Set(roots.flatMap(walk))];
|
|
183
|
+
const indexRel = provider.name === 'copilot' ? '.github/RULES-BOUND.md' : `.${provider.name}/RULES-BOUND.md`;
|
|
184
|
+
const indexFile = path.join(opts.target, indexRel);
|
|
185
|
+
const anchor = target => `${target.type}-${target.name}`.toLowerCase().replace(/[^a-z0-9_-]/g, '-');
|
|
186
|
+
const sections = new Map();
|
|
187
|
+
const targetsBySource = new Map();
|
|
188
|
+
for (const target of opts.ruleDelivery.targets) {
|
|
189
|
+
targetsBySource.set(target.source, [...(targetsBySource.get(target.source) || []), target]);
|
|
190
|
+
}
|
|
191
|
+
for (const file of files.filter(file => /\.(md|toml)$/.test(file))) {
|
|
192
|
+
if (path.basename(file) !== 'SKILL.md' && !/(?:[/\\](?:skills?|agents?|droids|commands?|prompts|modes?)[/\\])/.test(file)) continue;
|
|
193
|
+
if (/[/\\]rules[/\\]/.test(file) || /[/\\]\.aiwg[/\\](?!skills[/\\])/.test(file.replace(opts.target, ''))) continue;
|
|
194
|
+
let content = read(file);
|
|
195
|
+
if (!/aiwg:managed/.test(content) && !fs.existsSync(path.join(path.dirname(file), '.aiwg-managed')) && !fs.existsSync(path.join(path.dirname(file), '.aiwg-manifest.json'))) continue;
|
|
196
|
+
const skill = path.basename(file) === 'SKILL.md';
|
|
197
|
+
const name = skill ? path.basename(path.dirname(file)) : path.basename(file).replace(/\.(md|toml)$/, '');
|
|
198
|
+
const sidecarPath = path.join(skill ? path.dirname(file) : path.dirname(file), '.aiwg-manifest.json');
|
|
199
|
+
const sidecar = fs.existsSync(sidecarPath) ? JSON.parse(read(sidecarPath)) : null;
|
|
200
|
+
const source = sidecar?.skillSource ? path.join(sidecar.skillSource, 'SKILL.md') : sidecar?.managed?.[path.basename(file)]?.sourcePath;
|
|
201
|
+
const flowSource = opts.flowSkillSources?.get(file);
|
|
202
|
+
const targets = [...(flowSource ? targetsBySource.get(flowSource) || [] : []),
|
|
203
|
+
...(source ? targetsBySource.get(path.resolve(source)) || [] : opts.ruleDelivery.targets.filter(target =>
|
|
204
|
+
(skill ? target.type !== 'agent' : /[/\\](?:agents?|droids|modes?)[/\\]/.test(file) ? target.type === 'agent' : target.type === 'flow') &&
|
|
205
|
+
[target.name, path.basename(target.source, '.md'), path.basename(path.dirname(target.source))].includes(name)))];
|
|
206
|
+
const rules = targets.flatMap(target => opts.ruleDelivery.bindings.get(target.source) || []);
|
|
207
|
+
if (!rules.length && !content.includes('<!-- AIWG:bound-rules:start -->')) continue;
|
|
208
|
+
const pointer = body => {
|
|
209
|
+
const clean = replaceBoundRulesBlock(body, []);
|
|
210
|
+
if (!rules.length) return clean;
|
|
211
|
+
const identities = [...new Map(targets.map(target => [`${target.type} ${target.name}`, target])).values()];
|
|
212
|
+
for (const target of identities) {
|
|
213
|
+
const bound = opts.ruleDelivery.bindings.get(target.source) || [];
|
|
214
|
+
const unique = [...new Map(bound.map(rule => [rule.name, rule])).values()].sort((a, b) => a.name.localeCompare(b.name));
|
|
215
|
+
if (unique.length) sections.set(anchor(target), `## ${anchor(target)}\n\n` + unique.map(rule =>
|
|
216
|
+
`- ${rule.name} — ${rule.summary} Fetch and follow: \`aiwg show rule ${rule.name} --body\`.`).join('\n'));
|
|
217
|
+
}
|
|
218
|
+
// Skills must carry exact fetch commands themselves: a section pointer
|
|
219
|
+
// alone loses the invocation contract in clean installs (#3473).
|
|
220
|
+
const fetch = skill ? [...new Map(rules.map(rule => [rule.name, rule])).values()]
|
|
221
|
+
.sort((a, b) => a.name.localeCompare(b.name))
|
|
222
|
+
.map(rule => `${rule.summary}\nFetch and follow before governed work: \`aiwg show rule ${rule.name} --body\`.`).join('\n') : '';
|
|
223
|
+
return `${clean}${clean.endsWith('\n') ? '' : '\n'}\n<!-- AIWG:bound-rules:start -->\nRead and follow before governed work: ${identities.map(target =>
|
|
224
|
+
`\`${indexRel}#${anchor(target)}\``).join('; ')}.\n${fetch ? fetch + '\n' : ''}<!-- AIWG:bound-rules:end -->\n`;
|
|
225
|
+
};
|
|
226
|
+
if (file.endsWith('.toml')) content = content.replace(/^developer_instructions = (".*")$/m, (_, value) => `developer_instructions = ${JSON.stringify(pointer(JSON.parse(value)))}`);
|
|
227
|
+
else content = pointer(content);
|
|
228
|
+
put(file, content);
|
|
229
|
+
// Keep deployment hashes honest after projection by external helpers.
|
|
230
|
+
if (sidecar?.managed?.[path.basename(file)]) {
|
|
231
|
+
sidecar.managed[path.basename(file)].hash = `sha256:${contentHash(content)}`;
|
|
232
|
+
put(sidecarPath, `${JSON.stringify(sidecar, null, 2)}\n`);
|
|
233
|
+
}
|
|
234
|
+
}
|
|
235
|
+
if (sections.size) put(indexFile, managed('# Bound rules\n\nFetch and follow every full rule in the invoked artifact’s section before governed work.\n\n' +
|
|
236
|
+
[...sections.entries()].sort(([a], [b]) => a.localeCompare(b)).map(([, section]) => section).join('\n\n') + '\n', opts));
|
|
237
|
+
else if (/aiwg:managed/.test(read(indexFile))) fs.rmSync(indexFile);
|
|
238
|
+
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
/** Bindings annotate the selected deployment; they do not select standard skills
|
|
242
|
+
* (ADR lines 102–108). Flow projections follow the same opt-in and tier routing. */
|
|
243
|
+
export function projectBoundFlowSkills(opts, provider, selected) {
|
|
244
|
+
opts.flowSkillSources = new Map();
|
|
245
|
+
if (opts.rulesOnly || opts.commandsOnly || !(opts.deploySkills || opts.skillsOnly)) return;
|
|
246
|
+
const kernel = path.isAbsolute(provider.kernelSkillsPath || '') ? opts.kernelSkillsPath
|
|
247
|
+
: path.join(opts.target, provider.kernelSkillsPath || `.${provider.name}/skills`);
|
|
248
|
+
// Codex's opt-in standard tier shares the native skills directory.
|
|
249
|
+
const standard = provider.name === 'codex' ? kernel : path.isAbsolute(provider.paths.skills)
|
|
250
|
+
? provider.paths.skills : path.join(opts.target, provider.paths.skills);
|
|
251
|
+
const flows = opts.ruleDelivery.targets.filter(entry => entry.type === 'flow' && selected(entry));
|
|
252
|
+
const sources = new Set(flows.map(entry => entry.source));
|
|
253
|
+
for (const root of new Set([kernel, standard])) {
|
|
254
|
+
if (!fs.existsSync(root)) continue;
|
|
255
|
+
for (const entry of fs.readdirSync(root, { withFileTypes: true })) {
|
|
256
|
+
if (!entry.isDirectory()) continue;
|
|
257
|
+
const dir = path.join(root, entry.name);
|
|
258
|
+
const file = path.join(dir, 'SKILL.md');
|
|
259
|
+
const content = read(file);
|
|
260
|
+
const receiptFile = path.join(dir, '.aiwg-manifest.json');
|
|
261
|
+
const receipt = fs.existsSync(receiptFile) ? JSON.parse(read(receiptFile)) : null;
|
|
262
|
+
// Recognize the old projector's exact generated wrapper as well as new
|
|
263
|
+
// receipts. Ordinary deployed skills and operator files are preserved.
|
|
264
|
+
const legacy = !receipt?.skillSource && !receipt?.flowSource && /aiwg:managed/.test(content)
|
|
265
|
+
&& content.includes(`description: Invoke ${entry.name}.\n`)
|
|
266
|
+
&& content.includes('```yaml\n') && content.includes('<!-- AIWG:bound-rules:start -->');
|
|
267
|
+
const stale = receipt?.flowSource && (opts.copyStandardSkills !== true
|
|
268
|
+
|| !sources.has(receipt.flowSource) || root !== standard);
|
|
269
|
+
if (!legacy && !stale) continue;
|
|
270
|
+
fs.rmSync(file, { force: true });
|
|
271
|
+
if (receipt?.flowSource) {
|
|
272
|
+
fs.rmSync(receiptFile, { force: true });
|
|
273
|
+
fs.rmSync(path.join(dir, '.aiwg-managed'), { force: true });
|
|
274
|
+
}
|
|
275
|
+
if (!fs.readdirSync(dir).length) fs.rmdirSync(dir);
|
|
276
|
+
}
|
|
277
|
+
}
|
|
278
|
+
if (opts.copyStandardSkills !== true) return;
|
|
279
|
+
for (const entry of flows) {
|
|
280
|
+
const name = entry.name || path.basename(entry.source).replace(/\.(md|ya?ml)$/, '');
|
|
281
|
+
const dir = path.join(standard, name);
|
|
282
|
+
const file = path.join(dir, 'SKILL.md');
|
|
283
|
+
const receiptFile = path.join(dir, '.aiwg-manifest.json');
|
|
284
|
+
const receipt = fs.existsSync(receiptFile) ? JSON.parse(read(receiptFile)) : null;
|
|
285
|
+
// A selected authored skill may already represent this flow. Keep its body;
|
|
286
|
+
// finishBindings adds both artifact identities' contracts after projection.
|
|
287
|
+
if (!fs.existsSync(file) || receipt?.flowSource === entry.source) {
|
|
288
|
+
const body = read(entry.source);
|
|
289
|
+
const markdown = entry.source.endsWith('.md') ? body : `---\nname: ${name}\nnamespace: aiwg\ndescription: Invoke ${name}.\n---\n\n\`\`\`yaml\n${body}\n\`\`\`\n`;
|
|
290
|
+
const projected = provider.transformSkillMd ? provider.transformSkillMd(markdown, opts) : markdown;
|
|
291
|
+
const content = managed(replaceBoundRulesBlock(projected, opts.ruleDelivery.bindings.get(entry.source)), opts);
|
|
292
|
+
put(file, content);
|
|
293
|
+
put(path.join(dir, '.aiwg-managed'), 'true\n');
|
|
294
|
+
put(receiptFile, `${JSON.stringify({ flowSource: entry.source,
|
|
295
|
+
managed: { 'SKILL.md': { sourcePath: entry.source, hash: `sha256:${contentHash(content)}` } } }, null, 2)}\n`);
|
|
296
|
+
}
|
|
297
|
+
opts.flowSkillSources.set(file, entry.source);
|
|
298
|
+
if (['warp', 'hermes'].includes(provider.name)) opts.definitionRoutes.push(`${name}: ${file}`);
|
|
299
|
+
}
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
/** Count rule sections, excluding aggregated agent/command definitions and project prose. */
|
|
303
|
+
export function warpRuleContent(content) {
|
|
304
|
+
const blocks = [...content.matchAll(/<!-- AIWG:(rule-(?:startup|core|hook-[\w-]+)):start -->[\s\S]*?<!-- AIWG:\1:end -->/g)].map(match => match[0]);
|
|
305
|
+
// Remove managed blocks first so their internal headings cannot be counted twice.
|
|
306
|
+
const remaining = content.replace(/<!-- AIWG:(rule-(?:startup|core|hook-[\w-]+)):start -->[\s\S]*?<!-- AIWG:\1:end -->/g, '');
|
|
307
|
+
const sections = [...remaining.matchAll(/^## (?:AIWG Rules|On-Demand Rules)\r?\n[\s\S]*?(?=^## |(?![\s\S]))/gm)].map(match => match[0]);
|
|
308
|
+
return [...sections, ...blocks].join('\n');
|
|
309
|
+
}
|
|
310
|
+
|
|
311
|
+
export function startupFiles(opts, provider) {
|
|
312
|
+
const bridgeNames = { claude: ['CLAUDE.md'], cursor: ['AGENTS.md'], codex: ['AGENTS.md'], hermes: ['AGENTS.md', '.hermes.md'], pi: ['AGENTS.md'], warp: ['WARP.md'], openclaw: [] };
|
|
313
|
+
const paths = ['AIWG.md', 'WORKSPACE.md', ...(bridgeNames[provider.name] || ['AGENTS.md']), inlineStartup[provider.name]].filter(Boolean).map(name => path.join(opts.target, name));
|
|
314
|
+
if (opts.activeWorkspace) paths.push(path.join(opts.activeWorkspace, 'AGENTS.md'));
|
|
315
|
+
{
|
|
316
|
+
// Hook-reached files count too: moving a body must not hide its budget cost.
|
|
317
|
+
const dir = ruleDirectory(opts, provider);
|
|
318
|
+
paths.push(...walk(dir).filter(file => /\.(md|mdc)$/.test(file)));
|
|
319
|
+
}
|
|
320
|
+
return [...new Set(paths)].filter(file => fs.existsSync(file)).map(file => {
|
|
321
|
+
let content = read(file);
|
|
322
|
+
if (nativePathLoader(provider.name)) {
|
|
323
|
+
const parsed = parseRuleFrontmatter(content);
|
|
324
|
+
if (parsed.data?.paths || parsed.data?.globs) content = content.slice(0, content.length - parsed.body.length);
|
|
325
|
+
}
|
|
326
|
+
// Count managed rule sections while preserving historical accounting for
|
|
327
|
+
// operator aggregates; discrete hook-reached rule files are counted above.
|
|
328
|
+
if ((provider.name === 'warp' && path.basename(file) === 'WARP.md')
|
|
329
|
+
|| (provider.name === 'windsurf' && file === path.join(opts.target, 'AGENTS.md'))) content = warpRuleContent(content);
|
|
330
|
+
return { path: file, content };
|
|
331
|
+
});
|
|
332
|
+
}
|