@aiwg/cli 2026.11.1 → 2026.11.2
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-hooks/canonical/aiwg-prompt-discovery.yaml +9 -0
- package/agentic/code/addons/aiwg-hooks/hooks/aiwg-prompt-discovery.cjs +136 -0
- package/agentic/code/providers/model-capabilities.v1.json +27 -23
- package/agentic/code/providers/model-catalog.v1.json +3 -3
- package/dist/src/artifacts/cli.js +10 -11
- package/dist/src/artifacts/discover-cli-help.js +25 -0
- package/dist/src/artifacts/discover-session-facets.js +2 -1
- package/dist/src/artifacts/fortemi-core-prebuilt-freshness.js +28 -0
- package/dist/src/artifacts/fortemi-core-sync.js +3 -0
- package/dist/src/artifacts/framework-capabilities.js +4 -0
- package/dist/src/artifacts/framework-source-digest.js +1 -1
- package/dist/src/artifacts/index-builder.js +10 -10
- package/dist/src/artifacts/index-dependencies.js +72 -0
- package/dist/src/artifacts/query-engine-discover-output.js +13 -5
- package/dist/src/artifacts/query-engine-discover.js +49 -21
- package/dist/src/artifacts/query-engine-entries.js +56 -2
- package/dist/src/artifacts/query-engine-options.js +14 -1
- package/dist/src/artifacts/query-engine-scoring.js +8 -4
- package/dist/src/artifacts/query-engine-show-card.js +2 -0
- package/dist/src/artifacts/query-engine-show-load.js +1 -1
- package/dist/src/artifacts/query-engine-show.js +3 -1
- package/dist/src/artifacts/query-engine-templates.js +33 -0
- package/dist/src/artifacts/query-engine-verbose.js +25 -0
- package/dist/src/artifacts/relations-builder.js +49 -4
- package/dist/src/artifacts/relations.js +9 -0
- package/dist/src/artifacts/template-references.js +42 -0
- package/dist/src/artifacts/types.js +1 -1
- package/dist/src/cli/handlers/bundle-reconciliation.js +7 -3
- package/dist/src/cli/handlers/checkpoint-handoff.js +48 -0
- package/dist/src/cli/handlers/checkpoint-record.js +20 -0
- package/dist/src/cli/handlers/checkpoint.js +50 -17
- package/dist/src/cli/handlers/decision.js +1 -1
- package/dist/src/cli/handlers/doctor-args.js +3 -1
- package/dist/src/cli/handlers/doctor-help.js +2 -1
- package/dist/src/cli/handlers/help.js +1 -1
- package/dist/src/cli/handlers/refresh-bundles.js +2 -1
- package/dist/src/cli/handlers/refresh-managed-deployment.js +196 -0
- package/dist/src/cli/handlers/refresh.js +10 -2
- package/dist/src/cli/handlers/subcommands-discovery.js +8 -1
- package/dist/src/cli/handlers/use.js +10 -3
- package/dist/src/cli/services/deployment-verification.js +11 -7
- package/dist/src/config/worker-write.js +4 -10
- package/dist/src/decision/ledger.js +15 -15
- package/dist/src/decision/offload.js +6 -7
- package/dist/src/delivery/pr.js +2 -0
- package/dist/src/delivery/template-sections.js +56 -0
- package/dist/src/extensions/claude-hooks-installer.js +61 -53
- package/dist/src/extensions/managed-hook-script-state.js +48 -0
- package/dist/src/extensions/muse-managed-hooks.js +49 -0
- package/dist/src/issues/cli.js +3 -0
- package/dist/src/issues/external-cli.js +4 -1
- package/dist/src/issues/live.js +9 -2
- package/dist/src/issues/local.js +5 -1
- package/dist/src/issues/tracker-policy.js +11 -1
- package/dist/src/mcp/json-document.d.mts +2 -0
- package/dist/src/models/model-capabilities.v1.json +27 -23
- package/dist/src/models/model-catalog.v1.json +3 -3
- package/dist/src/models/provider-policy.js +8 -0
- package/dist/src/models/worker-health-readiness.js +20 -4
- package/dist/src/models/worker-health-snapshot.js +29 -0
- package/dist/src/models/worker-installation.d.mts +5 -1
- package/dist/src/models/worker-installation.mjs +11 -5
- package/dist/src/models/worker-qualification-policy.js +54 -0
- package/dist/src/providers/skill-ownership.d.mts +1 -0
- package/dist/src/providers/transformation-receipt-integration.js +4 -2
- package/dist/src/providers/transformation-receipt.js +4 -2
- package/dist/src/serve/worker-invocation.js +4 -2
- package/dist/src/smiths/context-pipeline/workspace-audit.js +34 -17
- package/dist/src/smiths/context-pipeline/workspace-context-shared.js +12 -6
- package/dist/src/smiths/context-pipeline/workspace-doctor.js +44 -4
- package/dist/src/smiths/context-pipeline/workspace-document.js +5 -2
- package/dist/src/smiths/context-pipeline/workspace-migration.js +2 -1
- package/dist/src/smiths/hook-bridge/codex-translator.js +150 -94
- package/dist/src/smiths/hook-bridge/codex-trust.js +50 -0
- package/dist/src/smiths/hook-bridge/factory-hook-config.js +132 -0
- package/dist/src/smiths/hook-bridge/factory-translator.js +88 -33
- package/dist/src/smiths/hook-bridge/index.js +3 -3
- package/dist/src/smiths/hook-bridge/loader.js +10 -2
- package/dist/src/smiths/hook-bridge/prompt-discovery-gaps.js +0 -1
- package/dist/src/storage/workspace-permissions-health.js +64 -0
- package/dist/src/storage/workspace-permissions.js +51 -0
- package/package.json +6 -1
- package/tools/agents/providers/base-files.mjs +2 -1
- package/tools/agents/providers/base-flat-artifacts.mjs +6 -3
- package/tools/agents/providers/base-models-platforms.mjs +3 -3
- package/tools/agents/providers/base-skill-copy.mjs +2 -0
- package/tools/agents/providers/bound-rules-pointer.mjs +21 -0
- package/tools/agents/providers/claude-post-deploy.mjs +9 -5
- package/tools/agents/providers/codex-post-deploy.mjs +10 -0
- package/tools/agents/providers/factory-hooks.mjs +43 -0
- package/tools/agents/providers/factory.mjs +4 -91
- package/tools/agents/providers/muse-hooks.mjs +4 -43
- package/tools/agents/providers/muse-prompt-discovery.mjs +3 -7
- package/tools/agents/providers/packaged-codex-agents.mjs +48 -0
- package/tools/agents/providers/rule-delivery-surface.mjs +4 -4
- package/tools/agents/providers/rule-presentation.mjs +6 -5
- package/tools/agents/providers/rule-projection.mjs +10 -2
- package/tools/agents/providers/rule-startup.mjs +8 -1
- package/tools/cli/decision-offload-report.mjs +7 -2
- package/tools/plugin/issue-template-copies.mjs +24 -0
- package/tools/plugin/package-plugins.mjs +11 -3
- package/tools/ralph-external/lib/factory-adapter.mjs +7 -8
- package/tools/ralph-external/lib/worker-artifacts.mjs +4 -2
- package/tools/ralph-external/lib/worker-final.mjs +43 -8
- package/tools/ralph-external/lib/worker-launch-cli.mjs +10 -1
- package/tools/ralph-external/lib/worker-prompt.mjs +35 -0
- package/tools/ralph-external/lib/worker-run-directory-refusal.mjs +8 -0
- package/tools/ralph-external/session-launcher.mjs +10 -7
|
@@ -4,9 +4,11 @@ import { diagnoseFacetActivations } from './discover-facets.js';
|
|
|
4
4
|
import { buildRunHint, DISCOVER_TYPE_ORDER, discoveryIdForEntry, normalizeIndexedPath, scopeRank, showHintForDiscoverResult, } from './query-engine-entries.js';
|
|
5
5
|
import { boundRuleDescriptor, compoundGoverningRules, governingRuleFields, governingRuleStats, RULE_CHECK_OBLIGATION, statsText, } from './query-engine-rules.js';
|
|
6
6
|
import { tokenize } from './query-engine-scoring.js';
|
|
7
|
-
import { ensureRelations } from './relations.js';
|
|
7
|
+
import { ensureRelations, loadRelations } from './relations.js';
|
|
8
|
+
import { templateRelationFields } from './query-engine-templates.js';
|
|
8
9
|
export async function emitDiscoverResults(context) {
|
|
9
|
-
const { cwd, params, types, limit, aiwgRoot, entries, backend, resourceSource, resolvedWebRelease, prebuiltRelations, prebuiltSelection, frameworkReconciled, scored, relaxed, queryTimeMs, lexicalDiagnostics } = context;
|
|
10
|
+
const { cwd, params, types, limit, aiwgRoot, entries, backend, resourceSource, resolvedWebRelease, prebuiltRelations, prebuiltSelection, frameworkReconciled, indexStale, scored, relaxed, queryTimeMs, lexicalDiagnostics } = context;
|
|
11
|
+
const readOnly = Boolean(params.noBuild || indexStale);
|
|
10
12
|
/**
|
|
11
13
|
* Resolve a stored framework-graph path to an absolute AIWG_ROOT
|
|
12
14
|
* path (#1217). Framework-graph entries are stored as paths relative
|
|
@@ -43,7 +45,8 @@ export async function emitDiscoverResults(context) {
|
|
|
43
45
|
: `No capability matched "${params.phrase}" among ${entries.length} indexed capabilities. Try a broader phrase or a \`--type\` filter. If you just installed or authored capabilities, refresh discovery with \`aiwg use <framework>\` (or \`aiwg index build\`).`
|
|
44
46
|
: null;
|
|
45
47
|
const relations = resourceSource === 'local' && (!params.graph || params.graph === 'framework')
|
|
46
|
-
? prebuiltRelations ??
|
|
48
|
+
? prebuiltRelations ?? (readOnly ? loadRelations(cwd, cwd, false)
|
|
49
|
+
: await ensureRelations(cwd, cwd, { verbose: params.verbose, selection: prebuiltSelection, reconciled: frameworkReconciled })) : undefined;
|
|
47
50
|
const governing = scored.map(result => compoundGoverningRules(entries, result.entry, relations ?? undefined, params.phrase));
|
|
48
51
|
const responseRules = new Map();
|
|
49
52
|
for (const item of governing.flat()) {
|
|
@@ -89,8 +92,7 @@ export async function emitDiscoverResults(context) {
|
|
|
89
92
|
},
|
|
90
93
|
};
|
|
91
94
|
};
|
|
92
|
-
const
|
|
93
|
-
const ruleRelations = relations ?? (resourceSource === 'local' ? loadRelations(cwd) ?? (aiwgRoot ? loadRelations(aiwgRoot, cwd) : null) : null);
|
|
95
|
+
const ruleRelations = relations ?? (resourceSource === 'local' ? loadRelations(cwd, cwd, !readOnly) ?? (aiwgRoot ? loadRelations(aiwgRoot, cwd, !readOnly) : null) : null);
|
|
94
96
|
if (params.json) {
|
|
95
97
|
const jsonIndent = params.jsonPretty === false ? undefined : 2;
|
|
96
98
|
console.log(JSON.stringify({
|
|
@@ -119,6 +121,7 @@ export async function emitDiscoverResults(context) {
|
|
|
119
121
|
type: r.entry.type,
|
|
120
122
|
name: r.entry.name,
|
|
121
123
|
title: r.entry.title,
|
|
124
|
+
...templateRelationFields(r.entry, ruleRelations, 3, includePaths),
|
|
122
125
|
score: Math.round(r.score * 100) / 100,
|
|
123
126
|
ranking: rankingDiagnostic(r.entry, r.score, r.facetDiagnostics),
|
|
124
127
|
...governingRuleFields(governing[resultIndex]),
|
|
@@ -146,6 +149,7 @@ export async function emitDiscoverResults(context) {
|
|
|
146
149
|
rule_stats: responseRuleStats,
|
|
147
150
|
...(responseFields.required_rule_checks ? { required_rule_checks: responseFields.required_rule_checks, rule_check_obligation: RULE_CHECK_OBLIGATION } : {}),
|
|
148
151
|
total: scored.length,
|
|
152
|
+
...(indexStale ? { stale: true } : {}),
|
|
149
153
|
query_time_ms: queryTimeMs,
|
|
150
154
|
diagnostics: {
|
|
151
155
|
content_tokens: tokenize(params.phrase),
|
|
@@ -210,6 +214,10 @@ export async function emitDiscoverResults(context) {
|
|
|
210
214
|
`scope ${ranking.tie_breakers.scope}`,
|
|
211
215
|
].filter((part) => Boolean(part));
|
|
212
216
|
console.log(` ranking: ${rankingParts.join('; ')}`);
|
|
217
|
+
for (const [key, items] of Object.entries(templateRelationFields(r.entry, ruleRelations, 3))) {
|
|
218
|
+
if (items?.length)
|
|
219
|
+
console.log(` ${key === 'templates' ? 'templates' : 'used by'}: ${items.map(item => `${item.name} (${item.show_command})`).join('; ')}`);
|
|
220
|
+
}
|
|
213
221
|
if (governing[i].length) {
|
|
214
222
|
console.log(` ${statsText(governingRuleStats(governing[i]))}`);
|
|
215
223
|
console.log(` ${RULE_CHECK_OBLIGATION}`);
|
|
@@ -2,17 +2,20 @@
|
|
|
2
2
|
import fs from 'node:fs';
|
|
3
3
|
import path from 'node:path';
|
|
4
4
|
import { applyFacetFusion, diagnoseFacetActivations } from './discover-facets.js';
|
|
5
|
-
import { refreshFrameworkCapabilities, resolveFrameworkCorpusRoot } from './framework-capabilities.js';
|
|
5
|
+
import { isIndexWritePermissionError, refreshFrameworkCapabilities, resolveFrameworkCorpusRoot } from './framework-capabilities.js';
|
|
6
6
|
import { resolveFrameworkIndexRoot } from './framework-index-paths.js';
|
|
7
7
|
import { loadGraphIndexFile, loadMetadataIndex } from './index-reader.js';
|
|
8
8
|
import { emitDiscoverResults } from './query-engine-discover-output.js';
|
|
9
|
-
import { compareDiscoverResults, dedupeDiscoverResults, DEFAULT_ARTIFACT_SEARCH_BACKEND, DEFAULT_DISCOVER_TYPES, defaultCapabilityGraphs, discoveryIdForEntry, isOrdinaryMemoryEntry, projectAllowsUserIndices, projectCapabilityFallback, withIndexProvenance, } from './query-engine-entries.js';
|
|
9
|
+
import { compareDiscoverResults, dedupeDiscoverResults, DEFAULT_ARTIFACT_SEARCH_BACKEND, DEFAULT_DISCOVER_TYPES, defaultCapabilityGraphs, discoveryIdForEntry, isOrdinaryMemoryEntry, projectAllowsUserIndices, projectCapabilityFallback, prepareProjectCapabilityIndex, withIndexProvenance, } from './query-engine-entries.js';
|
|
10
10
|
import { scoreEntryDetailed } from './query-engine-scoring.js';
|
|
11
|
-
import { emptyRuleStats, selectPrebuiltRelations } from './relations.js';
|
|
11
|
+
import { emptyRuleStats, selectPrebuiltRelations, loadBuiltRelations } from './relations.js';
|
|
12
|
+
import { templateRelationFields } from './query-engine-templates.js';
|
|
12
13
|
import { getGraphIndexDir, loadGlobalGraphConfigs } from './types.js';
|
|
13
14
|
export async function discoverCapability(cwd, params) {
|
|
14
15
|
loadGlobalGraphConfigs();
|
|
15
16
|
const startTime = Date.now();
|
|
17
|
+
const readOnly = Boolean(params.promptContext || params.noBuild);
|
|
18
|
+
let indexWriteFailure;
|
|
16
19
|
const types = params.typeFilter && params.typeFilter.length > 0
|
|
17
20
|
? params.typeFilter
|
|
18
21
|
: DEFAULT_DISCOVER_TYPES;
|
|
@@ -29,17 +32,17 @@ export async function discoverCapability(cwd, params) {
|
|
|
29
32
|
// project / codebase / legacy depending on what's available.
|
|
30
33
|
let entries = [];
|
|
31
34
|
let localFramework = null;
|
|
32
|
-
const backend =
|
|
35
|
+
const backend = readOnly ? 'local' : params.backend ?? DEFAULT_ARTIFACT_SEARCH_BACKEND;
|
|
33
36
|
let fortemiCoreDiscoveryScores = null;
|
|
34
|
-
let resourceSource =
|
|
37
|
+
let resourceSource = readOnly ? 'local' : params.resourceSource ?? 'local';
|
|
35
38
|
let resolvedWebRelease;
|
|
36
39
|
let verifiedSourcePaths;
|
|
37
40
|
const prebuiltSelection = resourceSource !== 'web' && (!params.graph || params.graph === 'framework')
|
|
38
|
-
? selectPrebuiltRelations(cwd, cwd, !
|
|
41
|
+
? selectPrebuiltRelations(cwd, cwd, !readOnly) : undefined;
|
|
39
42
|
const prebuiltRelations = prebuiltSelection?.reader ?? null;
|
|
40
43
|
// A valid prebuilt relationship package means the shipped index is current:
|
|
41
44
|
// never build a per-root framework index beside it (#3308, #2069 test).
|
|
42
|
-
if (!
|
|
45
|
+
if (!readOnly && (!prebuiltRelations || backend === 'local') && resourceSource !== 'web' && (!params.graph || params.graph === 'framework')) {
|
|
43
46
|
const root = resolveFrameworkCorpusRoot(cwd) ?? aiwgRoot;
|
|
44
47
|
if (root) {
|
|
45
48
|
try {
|
|
@@ -48,10 +51,17 @@ export async function discoverCapability(cwd, params) {
|
|
|
48
51
|
localFramework = loadGraphIndexFile(cwd, 'metadata.json', 'framework');
|
|
49
52
|
}
|
|
50
53
|
catch (error) {
|
|
51
|
-
|
|
54
|
+
if (isIndexWritePermissionError(error))
|
|
55
|
+
indexWriteFailure = 'framework';
|
|
56
|
+
else
|
|
57
|
+
console.error(`Warning: capability index refresh failed: ${error instanceof Error ? error.message : String(error)}`);
|
|
52
58
|
}
|
|
53
59
|
}
|
|
54
60
|
}
|
|
61
|
+
const projectBuildAttempted = !readOnly && !indexWriteFailure && resourceSource !== 'web' && (!params.graph || params.graph === 'project')
|
|
62
|
+
? await prepareProjectCapabilityIndex(cwd, () => { indexWriteFailure = 'project'; }) : false;
|
|
63
|
+
if (indexWriteFailure && resourceSource === 'auto')
|
|
64
|
+
resourceSource = 'local';
|
|
55
65
|
if (resourceSource === 'auto') {
|
|
56
66
|
const { loadFortemiCoreMetadataEntries } = await import('./fortemi-core-query-adapter.js');
|
|
57
67
|
const localGraphs = params.graph ? [params.graph] : defaultCapabilityGraphs(cwd);
|
|
@@ -96,6 +106,13 @@ export async function discoverCapability(cwd, params) {
|
|
|
96
106
|
: params.graph ? [params.graph] : defaultCapabilityGraphs(cwd);
|
|
97
107
|
let unavailableReason;
|
|
98
108
|
for (const graph of graphs) {
|
|
109
|
+
if (indexWriteFailure) {
|
|
110
|
+
const index = loadGraphIndexFile(cwd, 'metadata.json', graph);
|
|
111
|
+
if (Object.keys(index?.entries ?? {}).length) {
|
|
112
|
+
entries.push(...Object.values(index.entries).map(entry => withIndexProvenance(entry, graph)));
|
|
113
|
+
continue;
|
|
114
|
+
}
|
|
115
|
+
}
|
|
99
116
|
// Discovery ranks metadata, not full document bodies. A reconciled local
|
|
100
117
|
// framework index avoids parsing the much larger fulltext export.
|
|
101
118
|
if (graph === 'framework' && localFramework) {
|
|
@@ -106,21 +123,18 @@ export async function discoverCapability(cwd, params) {
|
|
|
106
123
|
const directory = getGraphIndexDir(cwd, graph);
|
|
107
124
|
if (!fs.existsSync(path.join(directory, 'metadata.json'))
|
|
108
125
|
&& !fs.existsSync(path.join(path.dirname(directory), 'fortemi-core', graph, 'manifest.json'))) {
|
|
109
|
-
if (graph === 'project')
|
|
126
|
+
if (graph === 'project' && !indexWriteFailure)
|
|
110
127
|
entries.push(...(projectCapabilityFallback(cwd) ?? []));
|
|
111
128
|
continue;
|
|
112
129
|
}
|
|
113
130
|
}
|
|
114
131
|
const { loadFortemiCoreMetadataEntries, queryFortemiCoreAiwgDiscovery } = await import('./fortemi-core-query-adapter.js');
|
|
115
132
|
const loaded = loadFortemiCoreMetadataEntries(cwd, graph, verifiedSourcePaths);
|
|
116
|
-
if (loaded.reason && graph === 'project' && !params.graph) {
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
entries.push(...fallback);
|
|
120
|
-
continue;
|
|
121
|
-
}
|
|
133
|
+
if (loaded.reason && !indexWriteFailure && graph === 'project' && (!params.graph || projectBuildAttempted)) {
|
|
134
|
+
entries.push(...(projectCapabilityFallback(cwd) ?? []));
|
|
135
|
+
continue;
|
|
122
136
|
}
|
|
123
|
-
if (loaded.sourceIndexNewer && resourceSource === 'local') {
|
|
137
|
+
if (loaded.sourceIndexNewer && resourceSource === 'local' && !indexWriteFailure) {
|
|
124
138
|
// Do not silently omit a graph whose derived cache is stale. Rank its
|
|
125
139
|
// current source metadata, without consulting scores from the old cache.
|
|
126
140
|
const index = loadGraphIndexFile(cwd, 'metadata.json', graph);
|
|
@@ -132,7 +146,7 @@ export async function discoverCapability(cwd, params) {
|
|
|
132
146
|
}
|
|
133
147
|
if (loaded.reason) {
|
|
134
148
|
unavailableReason ??= loaded.reason;
|
|
135
|
-
if (graph === 'framework' && !params.graph) {
|
|
149
|
+
if (graph === 'framework' && !params.graph && !indexWriteFailure) {
|
|
136
150
|
console.error(`Warning: framework capabilities are unavailable: ${loaded.reason}`);
|
|
137
151
|
}
|
|
138
152
|
}
|
|
@@ -153,7 +167,7 @@ export async function discoverCapability(cwd, params) {
|
|
|
153
167
|
}
|
|
154
168
|
}
|
|
155
169
|
}
|
|
156
|
-
if (entries.length === 0 && unavailableReason) {
|
|
170
|
+
if (entries.length === 0 && unavailableReason && !projectBuildAttempted && !indexWriteFailure) {
|
|
157
171
|
if (params.json) {
|
|
158
172
|
console.log(JSON.stringify({
|
|
159
173
|
query: {
|
|
@@ -188,6 +202,8 @@ export async function discoverCapability(cwd, params) {
|
|
|
188
202
|
const idx = loadGraphIndexFile(cwd, 'metadata.json', params.graph);
|
|
189
203
|
if (idx)
|
|
190
204
|
entries = Object.values(idx.entries).map((entry) => withIndexProvenance(entry, params.graph));
|
|
205
|
+
if (!readOnly && !indexWriteFailure && params.graph === 'project' && !entries.length)
|
|
206
|
+
projectCapabilityFallback(cwd);
|
|
191
207
|
}
|
|
192
208
|
else {
|
|
193
209
|
// discover is EXCLUSIVELY the agentic-capability surface (#1545): source
|
|
@@ -204,6 +220,8 @@ export async function discoverCapability(cwd, params) {
|
|
|
204
220
|
const projIdx = loadGraphIndexFile(cwd, 'metadata.json', 'project');
|
|
205
221
|
if (projIdx)
|
|
206
222
|
entries.push(...Object.values(projIdx.entries).map((entry) => withIndexProvenance(entry, 'project')));
|
|
223
|
+
if (!readOnly && !indexWriteFailure && !Object.keys(projIdx?.entries ?? {}).length)
|
|
224
|
+
projectCapabilityFallback(cwd);
|
|
207
225
|
if (includeUser) {
|
|
208
226
|
const userIdx = loadGraphIndexFile(cwd, 'metadata.json', 'user');
|
|
209
227
|
if (userIdx)
|
|
@@ -217,7 +235,7 @@ export async function discoverCapability(cwd, params) {
|
|
|
217
235
|
entries.push(...Object.values(legacy.entries));
|
|
218
236
|
}
|
|
219
237
|
}
|
|
220
|
-
if (
|
|
238
|
+
if (readOnly && prebuiltRelations) {
|
|
221
239
|
// Reuse the validated shipped export without refreshing or persisting receipts.
|
|
222
240
|
const { loadFortemiCoreMetadataEntries } = await import('./fortemi-core-query-adapter.js');
|
|
223
241
|
const loaded = loadFortemiCoreMetadataEntries(cwd, 'framework', undefined, prebuiltSelection);
|
|
@@ -226,11 +244,19 @@ export async function discoverCapability(cwd, params) {
|
|
|
226
244
|
entries.push(...loaded.entries.map(entry => withIndexProvenance(entry, 'framework')));
|
|
227
245
|
}
|
|
228
246
|
}
|
|
247
|
+
if (indexWriteFailure) {
|
|
248
|
+
if (!entries.length) {
|
|
249
|
+
const location = indexWriteFailure === 'framework' ? 'XDG_DATA_HOME' : 'AIWG_ARTIFACTS_PATH';
|
|
250
|
+
console.error(`Error: the capability index needs a writable location. Set ${location} to a writable directory and run \`aiwg index build --graph ${indexWriteFailure}\`.`);
|
|
251
|
+
process.exit(1);
|
|
252
|
+
}
|
|
253
|
+
console.error('Warning: capability index storage is not writable; using the existing index. Results may be stale.');
|
|
254
|
+
}
|
|
229
255
|
if (entries.length === 0 && params.promptContext) {
|
|
230
256
|
console.log(JSON.stringify({ results: [] }));
|
|
231
257
|
return;
|
|
232
258
|
}
|
|
233
|
-
if (entries.length === 0 && backend !== 'fortemi-core') {
|
|
259
|
+
if (entries.length === 0 && backend !== 'fortemi-core' && !params.noBuild && !projectBuildAttempted) {
|
|
234
260
|
// Empty-index case (#1221). Surface a hint that explains the gap rather
|
|
235
261
|
// than returning a bare zero-result envelope — the latter trains agents
|
|
236
262
|
// to conclude "AIWG doesn't have a skill for that" when in fact the
|
|
@@ -318,15 +344,17 @@ export async function discoverCapability(cwd, params) {
|
|
|
318
344
|
}
|
|
319
345
|
const queryTimeMs = Date.now() - startTime;
|
|
320
346
|
if (params.promptContext) {
|
|
347
|
+
const templateRelations = prebuiltRelations ?? loadBuiltRelations(cwd);
|
|
321
348
|
console.log(JSON.stringify({ results: scored.map(({ entry, score }) => ({
|
|
322
349
|
type: entry.type, name: entry.name ?? discoveryIdForEntry(entry),
|
|
350
|
+
...templateRelationFields(entry, templateRelations, 3, false),
|
|
323
351
|
capability: entry.type === 'rule'
|
|
324
352
|
? entry.ruleSummary || prebuiltRelations?.index.rules[discoveryIdForEntry(entry)]?.summary || entry.summary
|
|
325
353
|
: entry.capability ?? entry.summary, score,
|
|
326
354
|
})) }));
|
|
327
355
|
return;
|
|
328
356
|
}
|
|
329
|
-
await emitDiscoverResults({ cwd, params, types, limit, aiwgRoot, entries, backend, resourceSource,
|
|
357
|
+
await emitDiscoverResults({ cwd, params, indexStale: Boolean(indexWriteFailure), types, limit, aiwgRoot, entries, backend, resourceSource,
|
|
330
358
|
resolvedWebRelease, prebuiltRelations, prebuiltSelection, frameworkReconciled: Boolean(localFramework), scored, relaxed, queryTimeMs, lexicalDiagnostics });
|
|
331
359
|
}
|
|
332
360
|
//# sourceMappingURL=query-engine-discover.js.map
|
|
@@ -1,10 +1,11 @@
|
|
|
1
1
|
// Share entry identity, provenance, graph selection, and discovery ordering helpers.
|
|
2
|
-
import
|
|
2
|
+
import fs from 'node:fs';
|
|
3
3
|
import * as path from 'node:path';
|
|
4
4
|
import { projectAiwgPath, projectControlPath } from '../config/project-artifacts.js';
|
|
5
5
|
import { recordTypeForEntry, stableRecordId } from './browser-export.js';
|
|
6
6
|
import { loadGraphIndexFile } from './index-reader.js';
|
|
7
|
-
import {
|
|
7
|
+
import { isIndexWritePermissionError } from './framework-capabilities.js';
|
|
8
|
+
import { getGraphIndexDir, isOperationalShowType, OPERATIONAL_DISCOVERY_TYPES, loadUserGraphConfigs, GRAPH_CONFIGS, resolveGraphScanDir, } from './types.js';
|
|
8
9
|
export function normalizeIndexedPath(entryPath) {
|
|
9
10
|
return entryPath.replace(/\\/g, '/');
|
|
10
11
|
}
|
|
@@ -54,6 +55,59 @@ export function graphScope(graph) {
|
|
|
54
55
|
export function withIndexProvenance(entry, graph) {
|
|
55
56
|
return { ...entry, indexGraph: graph, indexScope: graphScope(graph) };
|
|
56
57
|
}
|
|
58
|
+
const projectBuilds = new Map();
|
|
59
|
+
/** Best-effort first-use preparation through the CLI's builder; return whether a build was attempted. */
|
|
60
|
+
export async function prepareProjectCapabilityIndex(cwd, onWriteFailure) {
|
|
61
|
+
const directory = getGraphIndexDir(cwd, 'project');
|
|
62
|
+
const pending = projectBuilds.get(directory);
|
|
63
|
+
const build = async () => {
|
|
64
|
+
let attempted = false;
|
|
65
|
+
let writeFailure;
|
|
66
|
+
try {
|
|
67
|
+
const index = loadGraphIndexFile(cwd, 'metadata.json', 'project');
|
|
68
|
+
if (Object.keys(index?.entries ?? {}).length)
|
|
69
|
+
return { attempted };
|
|
70
|
+
loadUserGraphConfigs(cwd);
|
|
71
|
+
// Avoid the explicit builder's missing-root exit and repeated empty builds.
|
|
72
|
+
if (!GRAPH_CONFIGS.project.scanDirs.some(dir => fs.existsSync(resolveGraphScanDir(cwd, dir))))
|
|
73
|
+
return { attempted };
|
|
74
|
+
const { collectGraphIndexFiles } = await import('./index-files.js');
|
|
75
|
+
if (!(await collectGraphIndexFiles(cwd, 'project')).length)
|
|
76
|
+
return { attempted };
|
|
77
|
+
fs.accessSync(cwd, fs.constants.W_OK);
|
|
78
|
+
let ancestor = directory;
|
|
79
|
+
while (!fs.existsSync(ancestor))
|
|
80
|
+
ancestor = path.dirname(ancestor);
|
|
81
|
+
fs.accessSync(ancestor, fs.constants.W_OK);
|
|
82
|
+
const { buildIndex } = await import('./index-builder.js');
|
|
83
|
+
attempted = true;
|
|
84
|
+
await buildIndex(cwd, { graph: 'project', quiet: true, explicit: false, lockWaitMs: 1000 });
|
|
85
|
+
// Match CLI build's derived-cache publication without its stdout progress.
|
|
86
|
+
const { syncFortemiCoreIndex } = await import('./fortemi-core-sync.js');
|
|
87
|
+
syncFortemiCoreIndex(cwd, { graph: 'project' });
|
|
88
|
+
}
|
|
89
|
+
catch (error) {
|
|
90
|
+
if (isIndexWritePermissionError(error))
|
|
91
|
+
writeFailure = error;
|
|
92
|
+
// The existing project fallback owns warnings and partial results.
|
|
93
|
+
}
|
|
94
|
+
// Permission failures get a single query-level diagnostic, including cold starts.
|
|
95
|
+
if (attempted && !writeFailure)
|
|
96
|
+
console.error('Building the project index for this workspace (first use)…');
|
|
97
|
+
return { attempted, writeFailure };
|
|
98
|
+
};
|
|
99
|
+
const promise = pending ?? build();
|
|
100
|
+
projectBuilds.set(directory, promise);
|
|
101
|
+
try {
|
|
102
|
+
const result = await promise;
|
|
103
|
+
if (result.writeFailure)
|
|
104
|
+
onWriteFailure?.(result.writeFailure);
|
|
105
|
+
return result.attempted;
|
|
106
|
+
}
|
|
107
|
+
finally {
|
|
108
|
+
projectBuilds.delete(directory);
|
|
109
|
+
}
|
|
110
|
+
}
|
|
57
111
|
/** Keep existing project capabilities visible while their derived cache is unavailable. */
|
|
58
112
|
export function projectCapabilityFallback(cwd) {
|
|
59
113
|
const index = loadGraphIndexFile(cwd, 'metadata.json', 'project');
|
|
@@ -1,2 +1,15 @@
|
|
|
1
|
-
export {
|
|
1
|
+
export async function readDiscoverPhrase(positional, flags, input = process.stdin) {
|
|
2
|
+
if (!flags.includes('--stdin'))
|
|
3
|
+
return positional.join(' ').trim();
|
|
4
|
+
if (positional.length > 0) {
|
|
5
|
+
throw new Error('--stdin cannot be combined with a positional search phrase');
|
|
6
|
+
}
|
|
7
|
+
const chunks = [];
|
|
8
|
+
for await (const chunk of input)
|
|
9
|
+
chunks.push(Buffer.from(chunk));
|
|
10
|
+
const phrase = Buffer.concat(chunks).toString('utf8').trim();
|
|
11
|
+
if (!phrase)
|
|
12
|
+
throw new Error('--stdin requires a non-empty search phrase');
|
|
13
|
+
return phrase;
|
|
14
|
+
}
|
|
2
15
|
//# sourceMappingURL=query-engine-options.js.map
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
// Tokenize discovery phrases and score metadata matches with lexical diagnostics.
|
|
2
2
|
import { diagnoseFacetActivations } from './discover-facets.js';
|
|
3
|
+
import { verboseQueryProfile } from './query-engine-verbose.js';
|
|
3
4
|
export function containsTokenSequence(haystack, needle) {
|
|
4
5
|
if (needle.length === 0 || haystack.length < needle.length)
|
|
5
6
|
return false;
|
|
@@ -170,13 +171,14 @@ export function scoreEntryDetailed(entry, text, opts = {}) {
|
|
|
170
171
|
// -> ["intake"]) must still match that token. Pure-stopword queries fall back
|
|
171
172
|
// to the raw text. Tokens are de-duplicated so a repeated word is credited once.
|
|
172
173
|
const tokens = [...new Set(tokenize(text))];
|
|
174
|
+
const verbose = verboseQueryProfile(text, tokens, tokenize);
|
|
173
175
|
const lower = tokens.length > 0 ? tokens.join(' ') : text.toLowerCase().trim();
|
|
174
176
|
const rawLower = text.toLowerCase().trim();
|
|
175
177
|
const personaIdentitySuppressed = opts.personaIdentitySuppressed ?? diagnoseFacetActivations(text).some((activation) => activation.facet === 'persona-identity' && activation.status === 'suppressed');
|
|
176
178
|
let score = 0;
|
|
177
179
|
const matches = [];
|
|
178
180
|
const creditedTokens = new Map();
|
|
179
|
-
const finish = (uncappedScore = score, cap = 1) => ({
|
|
181
|
+
const finish = (uncappedScore = score, cap = verbose?.coverage(matches) ?? 1) => ({
|
|
180
182
|
score: Math.min(uncappedScore, cap),
|
|
181
183
|
diagnostic: {
|
|
182
184
|
content_tokens: tokens,
|
|
@@ -187,13 +189,15 @@ export function scoreEntryDetailed(entry, text, opts = {}) {
|
|
|
187
189
|
},
|
|
188
190
|
});
|
|
189
191
|
const addMatch = (contribution, match) => {
|
|
192
|
+
contribution *= verbose?.weight(match.matched_tokens ?? tokens) ?? 1;
|
|
190
193
|
score += contribution;
|
|
191
194
|
matches.push({ ...match, contribution });
|
|
192
195
|
};
|
|
193
196
|
const addTokenMatch = (contributionPerToken, hits, match) => {
|
|
194
|
-
//
|
|
195
|
-
//
|
|
196
|
-
const denominator = match.field === 'trigger' && hits.length === 1
|
|
197
|
+
// Short queries discount sparse trigger overlap. Verbose queries instead
|
|
198
|
+
// apply token weights and the shared coverage cap across all fields.
|
|
199
|
+
const denominator = !verbose && match.field === 'trigger' && (hits.length === 1 || hits.length < Math.ceil(tokens.length / 2))
|
|
200
|
+
? Math.max(1, tokens.length) : 1;
|
|
197
201
|
const weight = contributionPerToken / denominator;
|
|
198
202
|
const newlyMatched = hits.filter(token => weight > (creditedTokens.get(token) ?? 0));
|
|
199
203
|
if (newlyMatched.length === 0)
|
|
@@ -6,6 +6,7 @@ import { extractMarkdownLinks, parseFlowDoc, parseFrontmatter } from './index-bu
|
|
|
6
6
|
import { buildRunHint, discoveryIdForEntry, normalizeIndexedPath } from './query-engine-entries.js';
|
|
7
7
|
import { RULE_CHECK_OBLIGATION, statsText } from './query-engine-rules.js';
|
|
8
8
|
import { emptyRuleStats } from './relations.js';
|
|
9
|
+
import { templateRelationLines } from './query-engine-templates.js';
|
|
9
10
|
/** Sections include their nested headings, stopping at the next peer/ancestor. */
|
|
10
11
|
export function showSections(content) {
|
|
11
12
|
const body = parseFrontmatter(content).body;
|
|
@@ -190,6 +191,7 @@ export async function emitShowCard(cwd, aiwgRoot, entry, filePath, source, param
|
|
|
190
191
|
lines.push(pinNote);
|
|
191
192
|
if ('activation' in card)
|
|
192
193
|
lines.push(`Activation: ${card.activation} | enforcement: ${card.enforcement}`, `Bound targets: ${JSON.stringify(card.bound_to)}`);
|
|
194
|
+
lines.push(...templateRelationLines(extra));
|
|
193
195
|
lines.push(contentNotice, bindings.text || RULE_CHECK_OBLIGATION, '\n## Outline', ...card.outline.map(section => `- ${section.heading} (${section.bytes} bytes, ${section.lines} lines)`), '\n## Resources', ...resources.map(resource => `- ${resource.path} (${resource.bytes} bytes)`), '\n## Drill in', ...Object.values(card.drill_in).flat().map(command => `- ${command}`));
|
|
194
196
|
if (card.resource)
|
|
195
197
|
lines.push(`\n## Resource: ${card.resource.path}`, card.resource.body);
|
|
@@ -46,7 +46,7 @@ export async function loadShowEntries(cwd, params, compact = false) {
|
|
|
46
46
|
const localEntries = params.graph ? [] : defaultCapabilityGraphs(cwd).filter(graph => graph !== 'framework')
|
|
47
47
|
.flatMap(graph => loadLocalCapabilityEntries(cwd, graph, undefined, true));
|
|
48
48
|
const compactEntries = [...localEntries, ...frameworkEntries];
|
|
49
|
-
if ((params.typeFilter?.every(type => ['skill', 'agent', 'flow', 'command', 'rule', 'behavior'].includes(type)))
|
|
49
|
+
if ((params.typeFilter?.every(type => ['skill', 'agent', 'flow', 'command', 'rule', 'behavior', 'template'].includes(type)))
|
|
50
50
|
|| findShowMatches(compactEntries, params.typeFilter ?? [...OPERATIONAL_SHOW_TYPES], params.name.trim()).length) {
|
|
51
51
|
return { entries: compactEntries, aiwgRoot, resourceSource: 'local', relations };
|
|
52
52
|
}
|
|
@@ -7,6 +7,7 @@ import { buildRunHint, DEFAULT_ARTIFACT_SEARCH_BACKEND, discoveryIdForEntry, nor
|
|
|
7
7
|
import { findShowMatches } from './query-engine-matching.js';
|
|
8
8
|
import { showBindings } from './query-engine-rules.js';
|
|
9
9
|
import { emitShowCard } from './query-engine-show-card.js';
|
|
10
|
+
import { templateRelationFields } from './query-engine-templates.js';
|
|
10
11
|
import { fortemiRecordForEntry, loadShowEntries, resolveMetadataPath } from './query-engine-show-load.js';
|
|
11
12
|
import { loadGlobalGraphConfigs, OPERATIONAL_SHOW_TYPES } from './types.js';
|
|
12
13
|
/**
|
|
@@ -68,7 +69,7 @@ export async function showArtifact(cwd, params) {
|
|
|
68
69
|
const fallbackEntry = { path: path.relative(aiwgRoot, corpusMatch.path), type: corpusMatch.type, name: needle, title: needle };
|
|
69
70
|
const bindings = await showBindings(entries, fallbackEntry, content, params, rule => fs.readFile(resolveMetadataPath(cwd, aiwgRoot, rule), 'utf8'), relations);
|
|
70
71
|
await emitShowCard(cwd, aiwgRoot, fallbackEntry, corpusMatch.path, content, params, bindings, { uninstalled: !installed, installed, hint: installHint,
|
|
71
|
-
...(localPin ? { local_pin: localPin } : {}) }, true);
|
|
72
|
+
...(localPin ? { local_pin: localPin } : {}), ...templateRelationFields(fallbackEntry, relations) }, true);
|
|
72
73
|
return;
|
|
73
74
|
}
|
|
74
75
|
}
|
|
@@ -171,6 +172,7 @@ export async function showArtifact(cwd, params) {
|
|
|
171
172
|
}, relations);
|
|
172
173
|
const providerModels = resourceSource === 'local' ? await loadProviderModelMetadata(cwd, aiwgRoot) : null;
|
|
173
174
|
await emitShowCard(cwd, aiwgRoot, entry, filePath, content, params, bindings, {
|
|
175
|
+
...templateRelationFields(entry, relations),
|
|
174
176
|
provenance: {
|
|
175
177
|
graph: entry.indexGraph ?? null,
|
|
176
178
|
scope: entry.indexScope ?? null,
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
// Shape template relationships consistently for show, discover, and prompt lookup.
|
|
2
|
+
import { discoveryIdForEntry } from './query-engine-entries.js';
|
|
3
|
+
export function templateRelationFields(entry, reader, limit = Infinity, includePaths = true) {
|
|
4
|
+
if (!reader)
|
|
5
|
+
return {};
|
|
6
|
+
const describe = (type, id, item) => {
|
|
7
|
+
const aliases = type === 'template' ? reader.index.aliases.templates?.[item.name]
|
|
8
|
+
: reader.index.aliases.targets[`${type}:${item.name}`];
|
|
9
|
+
const selector = aliases?.length === 1 && /^[a-zA-Z0-9][a-zA-Z0-9_.:-]*$/.test(item.name) ? item.name : id;
|
|
10
|
+
return { id, type, name: item.name, ...(includePaths ? { path: item.path } : {}), title: item.title ?? item.name,
|
|
11
|
+
show_command: `aiwg show ${type} ${selector}` };
|
|
12
|
+
};
|
|
13
|
+
const id = discoveryIdForEntry(entry);
|
|
14
|
+
if (entry.type === 'template') {
|
|
15
|
+
return { used_by: reader.targetsForTemplate(id).flatMap(target => {
|
|
16
|
+
const item = reader.index.targets[`${target.type}:${target.id}`];
|
|
17
|
+
return item ? [describe(target.type, target.id, { ...item, title: reader.index.artifacts?.[target.id]?.title })] : [];
|
|
18
|
+
}) };
|
|
19
|
+
}
|
|
20
|
+
if (!['skill', 'agent', 'flow', 'command'].includes(entry.type))
|
|
21
|
+
return {};
|
|
22
|
+
return { templates: reader.templatesForTarget(entry.type, id).slice(0, limit).flatMap(templateId => {
|
|
23
|
+
const template = reader.index.templates?.[templateId];
|
|
24
|
+
return template ? [describe('template', templateId, template)] : [];
|
|
25
|
+
}) };
|
|
26
|
+
}
|
|
27
|
+
export function templateRelationLines(fields) {
|
|
28
|
+
return Object.entries(fields).filter(([, items]) => items?.length).flatMap(([key, items]) => [
|
|
29
|
+
`\n## ${key === 'templates' ? 'Templates' : 'Used by'}`,
|
|
30
|
+
...items.map(item => `- ${item.name} (${item.type}): ${item.title} — \`${item.show_command}\``),
|
|
31
|
+
]);
|
|
32
|
+
}
|
|
33
|
+
//# sourceMappingURL=query-engine-templates.js.map
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
// Calibrate verbose-query evidence around the leading intent and weighted token coverage.
|
|
2
|
+
export function verboseQueryProfile(text, tokens, tokenize) {
|
|
3
|
+
// Short capability phrases retain their established lexical scores.
|
|
4
|
+
if (tokens.length <= 8)
|
|
5
|
+
return undefined;
|
|
6
|
+
const prose = text.replace(/(`+)[\s\S]*?\1/g, ' ');
|
|
7
|
+
const proseTokens = new Set(tokenize(prose));
|
|
8
|
+
const leading = new Set(tokenize(prose.split(/[.!?;:\n]/, 1)[0]).slice(0, 8));
|
|
9
|
+
const contextCount = tokens.filter(token => proseTokens.has(token) && !leading.has(token)).length;
|
|
10
|
+
// Context gets at most a quarter of the leading clause's total weight.
|
|
11
|
+
// Code-only words carry still less signal, but remain discoverable.
|
|
12
|
+
const contextWeight = Math.min(0.25, Math.max(1, leading.size) / (4 * Math.max(1, contextCount)));
|
|
13
|
+
const weights = new Map(tokens.map(token => [token,
|
|
14
|
+
leading.has(token) ? 1 : proseTokens.has(token) ? contextWeight : contextWeight * 0.2]));
|
|
15
|
+
const mass = (hits) => hits.reduce((sum, token) => sum + (weights.get(token) ?? 0), 0);
|
|
16
|
+
const total = mass(tokens);
|
|
17
|
+
return {
|
|
18
|
+
weight: (hits) => mass(hits) / Math.max(1, hits.length),
|
|
19
|
+
coverage: (matches) => {
|
|
20
|
+
const hits = [...new Set(matches.flatMap(match => match.matched_tokens ?? tokens))];
|
|
21
|
+
return total > 0 ? mass(hits) / total : 0;
|
|
22
|
+
},
|
|
23
|
+
};
|
|
24
|
+
}
|
|
25
|
+
//# sourceMappingURL=query-engine-verbose.js.map
|
|
@@ -8,6 +8,7 @@ import { resolveRuleBindingTarget } from './query-engine.js';
|
|
|
8
8
|
import { Minimatch } from 'minimatch';
|
|
9
9
|
import { FRAMEWORK_RELATIONS_REVISION } from './framework-source-digest.js';
|
|
10
10
|
import { writeIndexFile } from './index-reader.js';
|
|
11
|
+
import { createDependencyResolver } from './index-dependencies.js';
|
|
11
12
|
import { RELATIONS_SCHEMA, RELATIONS_VERSION, RULE_TIERS, emptyRuleStats, } from './relations.js';
|
|
12
13
|
const TARGET_TYPES = new Set(['skill', 'agent', 'flow', 'command']);
|
|
13
14
|
const BINDING_TYPES = { skills: 'skill', agents: 'agent', flows: 'flow' };
|
|
@@ -28,9 +29,9 @@ function owner(entry) {
|
|
|
28
29
|
const kind = { frameworks: 'framework', addons: 'addon', extensions: 'extension' }[match[1]];
|
|
29
30
|
return { id: `${kind}:${match[2]}`, kind };
|
|
30
31
|
}
|
|
31
|
-
/** Only rule/action sources affect this projection; no
|
|
32
|
+
/** Only rule/action/template sources affect this projection; no file rereads. */
|
|
32
33
|
export function relationsFingerprint(entries) {
|
|
33
|
-
const sources = entries.filter(entry => TARGET_TYPES.has(entry.type) || ['rule', 'behavior'].includes(entry.type))
|
|
34
|
+
const sources = entries.filter(entry => TARGET_TYPES.has(entry.type) || ['rule', 'behavior', 'template'].includes(entry.type))
|
|
34
35
|
.map(entry => [entry.path, entry.checksum]).sort((a, b) => a[0].localeCompare(b[0]));
|
|
35
36
|
return { version: RELATIONS_VERSION, sources: `sha256:${createHash('sha256').update(JSON.stringify({ projectionVersion: FRAMEWORK_RELATIONS_REVISION, extractorVersion: INDEX_EXTRACTOR_VERSION, sources })).digest('hex')}` };
|
|
36
37
|
}
|
|
@@ -50,10 +51,10 @@ function statsFor(ids, index) {
|
|
|
50
51
|
export function buildRelations(entries) {
|
|
51
52
|
const index = {
|
|
52
53
|
$schema: RELATIONS_SCHEMA, version: RELATIONS_VERSION, generatedAt: '1970-01-01T00:00:00.000Z',
|
|
53
|
-
fingerprint: relationsFingerprint(entries), artifacts: {}, rules: {}, targets: {}, capabilities: {}, aliases: { targets: {}, rules: {} },
|
|
54
|
+
fingerprint: relationsFingerprint(entries), artifacts: {}, rules: {}, templates: {}, targets: {}, capabilities: {}, aliases: { targets: {}, rules: {}, templates: {} },
|
|
54
55
|
};
|
|
55
56
|
for (const entry of [...entries].sort((a, b) => a.path.localeCompare(b.path))) {
|
|
56
|
-
if (!TARGET_TYPES.has(entry.type) && !['rule', 'behavior'].includes(entry.type))
|
|
57
|
+
if (!TARGET_TYPES.has(entry.type) && !['rule', 'behavior', 'template'].includes(entry.type))
|
|
57
58
|
continue;
|
|
58
59
|
const { path: sourcePath, type, name, title, kernel, script, governedPaths } = entry;
|
|
59
60
|
index.artifacts[relationId(entry)] = { path: sourcePath, type, title, ...(name ? { name } : {}), ...(kernel ? { kernel } : {}), ...(script ? { script } : {}), ...(governedPaths ? { governedPaths } : {}) };
|
|
@@ -150,8 +151,52 @@ export function buildRelations(entries) {
|
|
|
150
151
|
index.aliases.targets[`skill:projected:${target.name}`] = [key];
|
|
151
152
|
target.rule_stats = statsFor(target.rules, index);
|
|
152
153
|
}
|
|
154
|
+
addTemplateRelations(entries, index);
|
|
153
155
|
return index;
|
|
154
156
|
}
|
|
157
|
+
/** Project resolved index dependencies, including Markdown-link reverse edges. */
|
|
158
|
+
function addTemplateRelations(entries, index) {
|
|
159
|
+
const byPath = Object.fromEntries(entries.map(entry => [entry.path, entry]));
|
|
160
|
+
const resolve = createDependencyResolver(byPath);
|
|
161
|
+
const templates = entries.filter(entry => entry.type === 'template').sort((a, b) => a.path.localeCompare(b.path));
|
|
162
|
+
const link = (component, template) => {
|
|
163
|
+
if (!TARGET_TYPES.has(component.type))
|
|
164
|
+
return;
|
|
165
|
+
const target = index.targets[`${component.type}:${relationId(component)}`];
|
|
166
|
+
const id = relationId(template);
|
|
167
|
+
const edges = target.templates ??= [];
|
|
168
|
+
if (edges.includes(id))
|
|
169
|
+
return;
|
|
170
|
+
edges.push(id);
|
|
171
|
+
index.templates[id].used_by.push({ type: component.type, id: relationId(component) });
|
|
172
|
+
};
|
|
173
|
+
for (const template of templates) {
|
|
174
|
+
const id = relationId(template);
|
|
175
|
+
index.templates[id] = { name: template.name ?? slug(template), path: template.path, title: template.title, used_by: [] };
|
|
176
|
+
for (const alias of new Set([template.name, slug(template), template.path].filter((value) => !!value))) {
|
|
177
|
+
(index.aliases.templates[alias] ??= []).push(id);
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
for (const component of entries.filter(entry => TARGET_TYPES.has(entry.type))) {
|
|
181
|
+
for (const dependency of component.dependencies ?? []) {
|
|
182
|
+
const template = byPath[resolve(component.path, dependency) ?? ''];
|
|
183
|
+
if (template?.type === 'template')
|
|
184
|
+
link(component, template);
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
for (const template of templates)
|
|
188
|
+
for (const dependent of template.dependents ?? []) {
|
|
189
|
+
if (byPath[dependent])
|
|
190
|
+
link(byPath[dependent], template);
|
|
191
|
+
}
|
|
192
|
+
for (const target of Object.values(index.targets)) {
|
|
193
|
+
if (target.projected_from)
|
|
194
|
+
target.templates = [...(index.targets[`${target.projected_from.type}:${target.projected_from.id}`].templates ?? [])];
|
|
195
|
+
target.templates?.sort();
|
|
196
|
+
}
|
|
197
|
+
for (const template of Object.values(index.templates))
|
|
198
|
+
template.used_by.sort((a, b) => `${a.type}:${a.id}`.localeCompare(`${b.type}:${b.id}`));
|
|
199
|
+
}
|
|
155
200
|
export async function writeRelations(entries, cwd, indexDir, force = false, existingDir = indexDir) {
|
|
156
201
|
const values = Object.values(entries);
|
|
157
202
|
const fingerprint = relationsFingerprint(values);
|
|
@@ -25,6 +25,15 @@ export class RelationsReader {
|
|
|
25
25
|
this.index = index;
|
|
26
26
|
this.pinnedRuleIds = pinnedRuleIds;
|
|
27
27
|
}
|
|
28
|
+
templatesForTarget(type, id) {
|
|
29
|
+
const key = `${type}:${id}`;
|
|
30
|
+
const resolved = Object.hasOwn(this.index.targets, key) ? key : lookupAlias(this.index.aliases.targets, key);
|
|
31
|
+
return [...(resolved ? this.index.targets[resolved]?.templates ?? [] : [])];
|
|
32
|
+
}
|
|
33
|
+
targetsForTemplate(id) {
|
|
34
|
+
const resolved = Object.hasOwn(this.index.templates ?? {}, id) ? id : lookupAlias(this.index.aliases.templates ?? {}, id);
|
|
35
|
+
return resolved ? (this.index.templates?.[resolved]?.used_by ?? []).map(target => ({ ...target })) : [];
|
|
36
|
+
}
|
|
28
37
|
rulesForTarget(type, id) {
|
|
29
38
|
const key = `${type}:${id}`;
|
|
30
39
|
const resolved = Object.hasOwn(this.index.targets, key) ? key : lookupAlias(this.index.aliases.targets, key);
|