@aiwg/cli 2026.11.1 → 2026.11.3
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/capability-matrix.yaml +2 -2
- package/agentic/code/providers/model-capabilities.v1.json +44 -39
- 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/dataset.js +17 -0
- 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 +26 -5
- package/dist/src/cli/services/deployment-verification.js +11 -7
- package/dist/src/config/decision-config.js +2 -1
- package/dist/src/config/jev-credential-reference.js +56 -0
- package/dist/src/config/user-config.js +13 -19
- package/dist/src/config/worker-write.js +4 -10
- package/dist/src/decision/ask.js +3 -2
- package/dist/src/decision/jev-credentials.js +22 -0
- package/dist/src/decision/ledger.js +15 -15
- package/dist/src/decision/offload.js +7 -8
- package/dist/src/decision/openbao-kv-resolver.mjs +96 -0
- package/dist/src/decision/openbao-runtime.js +101 -0
- 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 +44 -39
- 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/capability-matrix.yaml +2 -2
- 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 +48 -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/factory-trust.js +56 -0
- 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 +9 -2
- package/tools/plugin/issue-template-copies.mjs +24 -0
- package/tools/plugin/package-plugins.mjs +17 -4
- package/tools/ralph-external/lib/claude-adapter.mjs +2 -2
- 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
|
@@ -30,6 +30,8 @@ import { collectGraphIndexFiles, findArtifactFiles, indexPathFor } from './index
|
|
|
30
30
|
import { acquireDirectoryLock } from './prebuilt-build-lock.js';
|
|
31
31
|
import { graphIndexDigest, indexAdapterRegistry, recordIndexVerification } from './index-adapters.js';
|
|
32
32
|
import { loadMemoryRecord } from '../memory/maintenance-record.js';
|
|
33
|
+
import { extractTemplateReferences, isTemplateReference } from './template-references.js';
|
|
34
|
+
import { createDependencyResolver, extractFlowDependencies } from './index-dependencies.js';
|
|
33
35
|
function absoluteEntryPath(cwd, entryPath, graph) {
|
|
34
36
|
if ((!graph || graph === 'project') && entryPath.startsWith(`${DEFAULT_PROJECT_AIWG_DIR}/`)) {
|
|
35
37
|
return path.join(resolveProjectAiwgDir(cwd), entryPath.slice(DEFAULT_PROJECT_AIWG_DIR.length + 1));
|
|
@@ -97,9 +99,10 @@ export function extractMentions(content) {
|
|
|
97
99
|
const pattern = /@(?:\$AIWG_ROOT\/)?(\.?aiwg\/[\w./-]+|[a-zA-Z][\w./-]+\.\w+)/g;
|
|
98
100
|
let match;
|
|
99
101
|
while ((match = pattern.exec(content)) !== null) {
|
|
100
|
-
|
|
102
|
+
if (!isTemplateReference(match[1]))
|
|
103
|
+
mentions.add(match[1]);
|
|
101
104
|
}
|
|
102
|
-
return
|
|
105
|
+
return [...new Set([...mentions, ...extractTemplateReferences(content)])];
|
|
103
106
|
}
|
|
104
107
|
/**
|
|
105
108
|
* Extract relative Markdown links that may resolve to graph-local artifacts.
|
|
@@ -812,6 +815,7 @@ export function parseFlowDoc(content, filePath) {
|
|
|
812
815
|
capability,
|
|
813
816
|
tags: labels,
|
|
814
817
|
searchTerms: [...searchTerms],
|
|
818
|
+
dependencies: extractFlowDependencies(spec),
|
|
815
819
|
};
|
|
816
820
|
}
|
|
817
821
|
/**
|
|
@@ -910,7 +914,7 @@ function extractIndexArtifact(job, bindingOnly, warnings = []) {
|
|
|
910
914
|
} };
|
|
911
915
|
const tags = flow?.tags ?? decision?.tags ?? gatePack?.tags ?? (Array.isArray(data.tags) ? data.tags.map(String) : []);
|
|
912
916
|
const summary = flow?.description ?? decision?.description ?? gatePack?.description ?? schemaDoc?.capability ?? runbook?.capability ?? extractSummary(data, body);
|
|
913
|
-
const dependencies = extractMentions(content);
|
|
917
|
+
const dependencies = [...new Set([...extractMentions(content), ...(flow?.dependencies ?? [])])];
|
|
914
918
|
const markdownLinks = extractMarkdownLinks(content);
|
|
915
919
|
// Discovery metadata (#1214, #1540, #1792) — meaningful for operational
|
|
916
920
|
// AIWG artifact kinds. Kept undefined on document types so the index file
|
|
@@ -1368,6 +1372,7 @@ async function buildIndexSnapshot(cwd, options, preparePublication, observation)
|
|
|
1368
1372
|
}
|
|
1369
1373
|
// Build tag reverse index
|
|
1370
1374
|
for (const entry of Object.values(entries)) {
|
|
1375
|
+
entry.dependents = []; // Recompute reverse edges even for reused incremental entries.
|
|
1371
1376
|
for (const tag of entry.tags) {
|
|
1372
1377
|
if (!tagIndex[tag])
|
|
1373
1378
|
tagIndex[tag] = [];
|
|
@@ -1376,18 +1381,13 @@ async function buildIndexSnapshot(cwd, options, preparePublication, observation)
|
|
|
1376
1381
|
}
|
|
1377
1382
|
// Build dependency graph and compute dependents
|
|
1378
1383
|
let markdownLinkEdgeCount = 0;
|
|
1379
|
-
const
|
|
1380
|
-
const dependencyPaths = new Map();
|
|
1384
|
+
const resolveDependency = createDependencyResolver(entries);
|
|
1381
1385
|
for (const entry of Object.values(entries)) {
|
|
1382
1386
|
if (!depGraph[entry.path]) {
|
|
1383
1387
|
depGraph[entry.path] = { upstream: [], downstream: [] };
|
|
1384
1388
|
}
|
|
1385
1389
|
for (const dep of entry.dependencies) {
|
|
1386
|
-
|
|
1387
|
-
if (!dependencyPaths.has(dep)) {
|
|
1388
|
-
dependencyPaths.set(dep, entryPaths.find(p => p === dep || p.endsWith(dep)));
|
|
1389
|
-
}
|
|
1390
|
-
const normalizedDep = dependencyPaths.get(dep);
|
|
1390
|
+
const normalizedDep = resolveDependency(entry.path, dep);
|
|
1391
1391
|
if (normalizedDep && normalizedDep !== entry.path) {
|
|
1392
1392
|
addDependencyEdge(depGraph, entries, entry.path, normalizedDep, 'depends-on');
|
|
1393
1393
|
}
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
// Resolve indexed file and declarative Flow references without per-edge scans.
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import { isTemplateReference, sourceBundleRoot, templateReferenceCandidates } from './template-references.js';
|
|
4
|
+
export function extractFlowDependencies(spec) {
|
|
5
|
+
const result = new Set();
|
|
6
|
+
const pending = [spec];
|
|
7
|
+
const seen = new Set();
|
|
8
|
+
while (pending.length) {
|
|
9
|
+
const value = pending.pop();
|
|
10
|
+
if (!value || typeof value !== 'object' || seen.has(value))
|
|
11
|
+
continue;
|
|
12
|
+
seen.add(value);
|
|
13
|
+
for (const [key, child] of Object.entries(value)) {
|
|
14
|
+
if (['body', 'content', 'script', 'source', 'template'].includes(key))
|
|
15
|
+
continue;
|
|
16
|
+
const kind = key === 'agent' ? 'agent'
|
|
17
|
+
: /^(?:capability|rollback[_-]?capability|playbook|flow)$/.test(key) ? 'flow' : undefined;
|
|
18
|
+
if (kind && typeof child === 'string' && /^[\w.-]+$/.test(child))
|
|
19
|
+
result.add(`${kind}:${child}`);
|
|
20
|
+
else if (child && typeof child === 'object')
|
|
21
|
+
pending.push(child);
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
return [...result];
|
|
25
|
+
}
|
|
26
|
+
function register(map, key, value) {
|
|
27
|
+
if (!map.has(key))
|
|
28
|
+
map.set(key, value);
|
|
29
|
+
else if (map.get(key) !== value)
|
|
30
|
+
map.set(key, null);
|
|
31
|
+
}
|
|
32
|
+
export function createDependencyResolver(entries) {
|
|
33
|
+
const suffixes = new Map();
|
|
34
|
+
const names = new Map();
|
|
35
|
+
for (const entry of Object.values(entries)) {
|
|
36
|
+
const file = entry.path;
|
|
37
|
+
for (let offset = file.indexOf('/'); offset >= 0; offset = file.indexOf('/', offset + 1)) {
|
|
38
|
+
register(suffixes, file.slice(offset + 1), file);
|
|
39
|
+
}
|
|
40
|
+
if (['agent', 'flow', 'runbook'].includes(entry.type)) {
|
|
41
|
+
// Flow agent fields use file slugs even when frontmatter names are titles
|
|
42
|
+
// (for example, project-manager.md declares name: Project Manager).
|
|
43
|
+
const basename = path.posix.basename(file);
|
|
44
|
+
const slug = /^(AGENT|FLOW)\.md$/i.test(basename)
|
|
45
|
+
? path.posix.basename(path.posix.dirname(file)) : basename.replace(/\.[^.]+$/, '');
|
|
46
|
+
for (const alias of new Set([entry.name, slug].filter(Boolean))) {
|
|
47
|
+
const name = `${entry.type === 'agent' ? 'agent' : 'flow'}:${alias}`;
|
|
48
|
+
register(names, name, file);
|
|
49
|
+
register(names, `${sourceBundleRoot(file) ?? ''}|${name}`, file);
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
return (source, dep) => {
|
|
54
|
+
if (isTemplateReference(dep)) {
|
|
55
|
+
return templateReferenceCandidates(source, dep).find(candidate => entries[candidate]);
|
|
56
|
+
}
|
|
57
|
+
if (/^(agent|flow):/.test(dep)) {
|
|
58
|
+
const local = `${sourceBundleRoot(source) ?? ''}|${dep}`;
|
|
59
|
+
return (names.has(local) ? names.get(local) : names.get(dep)) ?? undefined;
|
|
60
|
+
}
|
|
61
|
+
if (entries[dep])
|
|
62
|
+
return dep;
|
|
63
|
+
// A bare filename (`@CLAUDE.md`, `@AIWG.md`) names a project or sibling file, not
|
|
64
|
+
// any indexed file that happens to share the basename (for example a template).
|
|
65
|
+
if (!dep.includes('/')) {
|
|
66
|
+
const sibling = path.posix.join(path.posix.dirname(source), dep);
|
|
67
|
+
return entries[sibling] ? sibling : undefined;
|
|
68
|
+
}
|
|
69
|
+
return suffixes.get(dep) ?? undefined;
|
|
70
|
+
};
|
|
71
|
+
}
|
|
72
|
+
//# sourceMappingURL=index-dependencies.js.map
|
|
@@ -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
|