pi-braid 0.40.5 → 0.41.0
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/AGENTS.md +17 -18
- package/README.md +128 -130
- package/TOOLS.md +35 -35
- package/build-info.json +4 -4
- package/dist/extensions/core/agent-environment/index.js +4 -3
- package/dist/extensions/core/prompt-builder/index.js +12 -7
- package/dist/extensions/core/prompt-builder/instance-composition.d.ts +51 -10
- package/dist/extensions/core/prompt-builder/instance-composition.js +87 -14
- package/dist/extensions/core/prompt-builder/system-info-tool.d.ts +3 -3
- package/dist/extensions/core/prompt-builder/system-info-tool.js +3 -3
- package/dist/extensions/core/prompt-builder/tool-guidelines.js +1 -1
- package/dist/extensions/core/skills-tool/auto-inject.d.ts +89 -10
- package/dist/extensions/core/skills-tool/auto-inject.js +150 -21
- package/dist/extensions/core/skills-tool/index.d.ts +70 -2
- package/dist/extensions/core/skills-tool/index.js +149 -15
- package/dist/extensions/core/skills-tool/reach.d.ts +119 -0
- package/dist/extensions/core/skills-tool/reach.js +213 -0
- package/dist/extensions/core/skills-tool/skill-triggers.d.ts +47 -10
- package/dist/extensions/core/skills-tool/skill-triggers.js +66 -23
- package/dist/extensions/enforcement/handlers/register-session-compact.js +12 -1
- package/dist/extensions/enforcement/handlers/register-session-shutdown-resumption.js +15 -34
- package/dist/extensions/enforcement/handlers/register-session-start-discoverability.d.ts +2 -1
- package/dist/extensions/enforcement/handlers/register-session-start-discoverability.js +55 -28
- package/dist/extensions/enforcement/handlers/register-turn-end-hygiene.d.ts +14 -10
- package/dist/extensions/enforcement/handlers/register-turn-end-hygiene.js +88 -82
- package/dist/extensions/enforcement/resume-state.d.ts +76 -0
- package/dist/extensions/enforcement/resume-state.js +90 -0
- package/dist/extensions/enforcement/substate/context-hygiene-state.d.ts +9 -0
- package/dist/extensions/enforcement/substate/context-hygiene-state.js +8 -0
- package/dist/extensions/enforcement/whisper.d.ts +12 -0
- package/dist/extensions/enforcement/whisper.js +16 -1
- package/dist/extensions/heartbeat/heartbeat-scheduler/index.js +14 -6
- package/dist/extensions/heartbeat/heartbeat-scheduler/policies.d.ts +7 -0
- package/dist/extensions/heartbeat/heartbeat-scheduler/policies.js +372 -0
- package/dist/extensions/memory/context-manager/handlers/tools/context-compress.d.ts +8 -2
- package/dist/extensions/memory/context-manager/handlers/tools/context-compress.js +54 -21
- package/dist/lib/config/braid-paths.d.ts +14 -0
- package/dist/lib/config/braid-paths.js +18 -0
- package/dist/lib/config/braid-settings.d.ts +21 -0
- package/dist/lib/config/braid-settings.js +16 -0
- package/dist/lib/detection/context-tiers.d.ts +47 -3
- package/dist/lib/detection/context-tiers.js +122 -13
- package/dist/lib/events/turn-boundary.d.ts +78 -0
- package/dist/lib/events/turn-boundary.js +91 -0
- package/dist/lib/orchestrator/workers.d.ts +3 -2
- package/dist/lib/orchestrator/workers.js +22 -4
- package/dist/lib/state/global-state.d.ts +1 -1
- package/docs/CONTEXT-MAP.md +1 -1
- package/docs/CONTEXT-POLICY.md +8 -0
- package/docs/FLEET.md +99 -0
- package/docs/LOCAL_DEV.md +0 -1
- package/docs/ROADMAP.md +5 -5
- package/docs/SETUP.md +19 -18
- package/package.json +5 -1
- package/scripts/fleet/cli.mjs +499 -0
- package/scripts/fleet/driver-rpc.mjs +376 -0
- package/scripts/fleet/driver-scripted.mjs +239 -0
- package/scripts/fleet/journal.mjs +994 -0
- package/scripts/fleet/procs.mjs +76 -0
- package/scripts/fleet/supervisor.mjs +1494 -0
- package/scripts/fleet/tool-guard.mjs +467 -0
- package/skills/herdr-topology/SKILL.md +6 -1
- package/skills/release-pipeline/SKILL.md +20 -4
- package/skills/research/SKILL.md +32 -0
- package/skills/subagent-orchestration/SKILL.md +2 -2
- package/src/extensions/core/agent-environment/index.ts +4 -3
- package/src/extensions/core/prompt-builder/AGENTS.md +8 -4
- package/src/extensions/core/prompt-builder/index.ts +12 -7
- package/src/extensions/core/prompt-builder/instance-composition.ts +98 -14
- package/src/extensions/core/prompt-builder/system-info-tool.ts +3 -3
- package/src/extensions/core/prompt-builder/tool-guidelines.ts +1 -1
- package/src/extensions/core/skills-tool/auto-inject.ts +196 -24
- package/src/extensions/core/skills-tool/index.ts +217 -15
- package/src/extensions/core/skills-tool/reach.ts +256 -0
- package/src/extensions/core/skills-tool/skill-triggers.ts +90 -20
- package/src/extensions/enforcement/handlers/register-session-compact.ts +12 -1
- package/src/extensions/enforcement/handlers/register-session-shutdown-resumption.ts +23 -36
- package/src/extensions/enforcement/handlers/register-session-start-discoverability.ts +59 -29
- package/src/extensions/enforcement/handlers/register-turn-end-hygiene.ts +101 -81
- package/src/extensions/enforcement/resume-state.ts +127 -0
- package/src/extensions/enforcement/substate/context-hygiene-state.ts +17 -0
- package/src/extensions/enforcement/whisper.ts +21 -1
- package/src/extensions/heartbeat/heartbeat-scheduler/index.ts +20 -5
- package/src/extensions/heartbeat/heartbeat-scheduler/policies.ts +370 -0
- package/src/extensions/memory/AGENTS.md +25 -1
- package/src/extensions/memory/context-manager/handlers/tools/context-compress.ts +80 -27
- package/src/lib/config/braid-paths.ts +20 -0
- package/src/lib/config/braid-settings.ts +46 -0
- package/src/lib/detection/context-tiers.ts +186 -13
- package/src/lib/events/AGENTS.md +1 -0
- package/src/lib/events/turn-boundary.ts +115 -0
- package/src/lib/orchestrator/workers.ts +33 -12
- package/src/lib/state/global-state.ts +1 -0
- package/src/lib/utils/AGENTS.md +1 -1
- package/src/types/extension-context.d.ts +22 -79
|
@@ -19,28 +19,32 @@ Every file in this folder either:
|
|
|
19
19
|
## Ownership
|
|
20
20
|
|
|
21
21
|
| File | Purpose |
|
|
22
|
-
| ------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
22
|
+
| ------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
23
23
|
| `index.ts` | Main handler. Wires `before_agent_start`, calls the 4 `deliver*` functions, composes the final prompt. |
|
|
24
24
|
| `section.ts` | The `PromptSection` primitive + `composeSections` joiner + `simpleSection`, `linesSection`, `headingSection` builders. |
|
|
25
25
|
| `identity.ts` | Framing constants: `IDENTITY_INTRO` (generalist identity), `DISCOVERY` (D1 guarded exploration stance), `WORK_ETHIC` (methodical precision, signal-not-noise), `REPAIR_DISCIPLINE` (root cause named falsifiably before repair; re-derivation of claims that are not yours; weighted repair decisions), `SELF_MANAGEMENT` (memory workspace, evidence-carrying done items, known-open-check done gate), `COMMUNICATION` (conclusion-first, output style), `EPISTEMIC_STANCE` (identity-core: claim gate, self-state gate, retrieved-context preference), `SELF_AUDIT` (symmetric doubt; handoff ends with the unverified), `PHILOSOPHY` (character-level stance - silence, calm strategist, precise self-irony). |
|
|
26
26
|
| `surface-discipline-section.ts` | `SURFACE_DISCIPLINE` (signal discipline across code, commits, tests, docs, reports, logs) + `surfaceDisciplineSection()` - its own section, rendered between the identity and identity-core blocks. Text pinned verbatim by test-prompt-budget.mjs. |
|
|
27
|
-
| `instance-composition.ts` | **v3.8** Instance
|
|
27
|
+
| `instance-composition.ts` | **v3.8** Full Instance block: agent identity + pi-core version + core root + cwd + settings dir + os/pid + session (id + elapsed/last-event/turns/tool-avg) + top-level extension packages. Served on demand by the `system_info` tool. The prompt carries `renderCompactInstance`: braid build + install root, model, PID, session id, and skill/memory counts (process-stable facts only; see Local Contracts). |
|
|
28
28
|
| `top-level-extensions.ts` | **v3.8** Discovery logic for top-level pi extension PACKAGES. Reads pi-core's `packages` field from `<cwd>/.pi/settings.json` (project) and `~/.pi/agent/settings.json` (user-global); project wins on collision. Resolves `npm:` specs in pi's managed install tree (`<agentDir>/npm/node_modules`) first, falling back to the global npm root (`npm root -g`); resolves local paths in place. Source tags: `project` / `user-global`. |
|
|
29
29
|
| `project-docs-section.ts` | Project docs (AGENTS.md / CLAUDE.md) pointer-only rendering as plain-text bullets (`- <basename> at <path>`). Mirrors the skills discoverability model but uses plain text (no XML tags) so the system prompt stays prose. Includes fingerprint cache and `RESOURCES_DISCOVER` invalidation. |
|
|
30
30
|
| `memory-section.ts` | Memory store pointer block (episodes + semantic + heuristics) as plain-text bullets (`- episodes at PATH`; count-free - per-store counts go stale at print time and are not rendered). Mirrors project-docs. Cached per session (static content, no fingerprint needed); invalidated on `RESOURCES_DISCOVER`. |
|
|
31
31
|
| `context-section.ts` | **v3.6** body fragment for the unified context block: context %, session health, steps-since-checkpoint. Returns `""` when nothing to surface. Composer (`index.ts`) joins this with project-docs and memory bodies. No heading. (Memory stores render pointer-only: per-store entry counts are not rendered; the whisper carries token counts, not memory counts.) |
|
|
32
32
|
| `awareness-whisper.ts` | Once-per-session context-hygiene steer whisper (customType `hygiene`): tokens in context + delta since the previous emission's baseline, the inspector pointer, and the injection-channel catalog; `formatAwarenessText` is tool-availability-aware; the TG inbound row is state-aware: it asserts reachability only when the poller liveness registry (`lib/state/telegram-poller-liveness.ts`) says the poller is running, else it hedges and names `telegram_poller status`. The catalog describes subsystem whispers by their stable envelope (produced by `lib/utils/whisper-format.ts`) instead of enumerating subsystems. |
|
|
33
33
|
| ~~`contrast-phrases.ts`~~ | **DELETED 2026-08-12 (keep+cut)** - legacy RepE-style phrase library (TRUTH_FIRST, ANTI_SYCOPHANCY, EPISTEMIC_STABILITY, KNOWLEDGE_BOUNDARY). Consolidated into `EPISTEMIC_STANCE` (identity.ts) on 2026-07-16; zero importers; provenance in the deleted file's git history. |
|
|
34
|
-
| ~~`resources-section.ts`~~ | **DELETED** - the `Resources: N skills` pointer line was dead: duplicated by the skills-loading contract and the list_skills tool description.
|
|
34
|
+
| ~~`resources-section.ts`~~ | **DELETED** - the standalone `Resources: N skills` pointer line was dead: duplicated by the skills-loading contract and the list_skills tool description. The counts return only on the compact instance line (`Resources: N skills, M memories`) as a load signal. `excludeSkillsBlock` in `inspect.ts` keeps its Resources parser (absent-degrades-to-0) for non-braid prompt shapes. |
|
|
35
35
|
| `tool-pipelines.ts` | Guarded multi-tool usage pipelines (research/debugging - the implementation pipeline was dropped, merged into COMMUNICATION's understand-before-act; the verification pipeline was dropped as a restatement of the verify/verify_claim/finalize rows); pinned by test-tool-pipelines.mjs. |
|
|
36
36
|
| `tool-guidelines.ts` | Per-tool guideline sync: `TOOL_GUIDELINES` (tool → one-line reflection, synced 1:1 with `packages/core/TOOLS.md`; mirror when-nots were trimmed and description restatements) + `perToolGuidelines()` `if has <tool>`-gated renderer + `resolveOwnedToolLine()` (tools-section resolver: owned lines only, the description fallback renders no row); pinned by the `tool-guidelines` describe block in test-tool-pipelines.mjs. |
|
|
37
37
|
| `pi-reference-section.ts` | Pi docs seat: `PI_REFERENCE_POINTER` + `piReferenceSection()` - a static pointer to the `pi-reference` skill (docs index + install paths), rendered after the tools section. Replaced the native `<docs>` re-emission; the parity registry marks the native `docs` key dropped. |
|
|
38
|
-
| `system-info-tool.ts` | `system_info` tool: full Instance data on demand (detail
|
|
38
|
+
| `system-info-tool.ts` | `system_info` tool: full Instance data on demand (detail full or compact). The seat for volatile facts (elapsed, last event, turns, tool average) and the core/cwd/settings path triple; a tool result is not a cached prefix. |
|
|
39
39
|
| `inspect.ts` | `prompt_inspect` tool: reads the actual system prompt from runtime. |
|
|
40
40
|
| `tool-description-trim.ts` | Third-party tool-description trim: `before_provider_request` handler that shortens registered descriptions of `herdr_*` tools to 1-2 lines in the API tools channel (curated map + prefix fallback); the deep form moved to the `herdr-topology` skill (progressive disclosure). When-gate preserved in every rewrite. |
|
|
41
41
|
|
|
42
42
|
## Local Contracts
|
|
43
43
|
|
|
44
|
+
### Compact instance line (volatility rule)
|
|
45
|
+
|
|
46
|
+
`renderCompactInstance` renders the one-line `instance` section in the system prompt. The system prompt is a cached prefix, so the line carries process-stable facts only: braid build + install root, model (provider/id), PID, session id, and skill/memory counts. A timestamp, elapsed time, turn count, tool average, or context size would rewrite that prefix on every request and cost more than the field is worth; those facts stay in the `system_info` tool, which is a fresh turn by construction. The counts answer "did the skill pack and memory stores load", not "how many exactly". `test-instance-block.mjs` pins the line: no cwd field, no timestamp or duration token, and a 320-byte cap.
|
|
47
|
+
|
|
44
48
|
### Identity vs behaviors (architectural split)
|
|
45
49
|
|
|
46
50
|
This folder holds the **shared identity layer** -- IDENTITY framings, not project-specific behaviors. The split:
|
|
@@ -40,7 +40,7 @@ import {
|
|
|
40
40
|
} from "./project-docs-section.js";
|
|
41
41
|
import { setCachedSkills, getCachedVisibleSkillNames } from "../skills-tool/index.js";
|
|
42
42
|
import { reconstructMemorySection, resetMemorySectionCache } from "./memory-section.js";
|
|
43
|
-
import { gatherInstanceData } from "./instance-composition.js";
|
|
43
|
+
import { gatherInstanceData, renderCompactInstance } from "./instance-composition.js";
|
|
44
44
|
import { sendTrackedMessage } from "../../../lib/utils/injection-tracker.js";
|
|
45
45
|
import { formatLocalTime } from "../../../lib/utils/local-time.js";
|
|
46
46
|
import { flushRecoveredFires } from "../../../extensions/scheduling/timer/wake-retry.js";
|
|
@@ -434,7 +434,10 @@ export default function promptBuilderExtension(pi: ExtensionAPI) {
|
|
|
434
434
|
} catch {
|
|
435
435
|
/* already init'd or non-fatal */
|
|
436
436
|
}
|
|
437
|
-
|
|
437
|
+
// getAll(limit) slices the in-memory store, so a small limit turned the
|
|
438
|
+
// rendered memory count into a floor of 3. The instance line reports a
|
|
439
|
+
// true count: ask for the whole store.
|
|
440
|
+
memoryCount = memory.getAll(Number.MAX_SAFE_INTEGER).length;
|
|
438
441
|
} catch {
|
|
439
442
|
/* memory unavailable - non-fatal */
|
|
440
443
|
}
|
|
@@ -480,9 +483,12 @@ export default function promptBuilderExtension(pi: ExtensionAPI) {
|
|
|
480
483
|
// Build the prompt as a flat list of sections. Every section is a
|
|
481
484
|
// `PromptSection`; the top-level handler never touches raw strings
|
|
482
485
|
// or arrays of strings.
|
|
483
|
-
// Instance: compact
|
|
484
|
-
//
|
|
485
|
-
//
|
|
486
|
+
// Instance: compact one-line orientation (build + install root, model,
|
|
487
|
+
// PID, session, resource counts); full data stays in the system_info
|
|
488
|
+
// tool. The block carries process-stable facts only: the system prompt
|
|
489
|
+
// is a cached prefix, so a field that changes between turns (a clock,
|
|
490
|
+
// elapsed time, turn or tool counters, context size) would invalidate
|
|
491
|
+
// that prefix on every request and cost more than the field is worth.
|
|
486
492
|
const instanceData = await gatherInstanceData(pi, ctx, {
|
|
487
493
|
skillCount: skills.length,
|
|
488
494
|
skillDirs,
|
|
@@ -493,8 +499,7 @@ export default function promptBuilderExtension(pi: ExtensionAPI) {
|
|
|
493
499
|
})),
|
|
494
500
|
memoryCount,
|
|
495
501
|
});
|
|
496
|
-
const
|
|
497
|
-
const compactInstanceLine = `Agent: Braid v${instanceData.braidVersion} (over pi-core v${instanceData.pi.version}) | Cwd: ${instanceData.cwd} | Session: ${sessionId}`;
|
|
502
|
+
const compactInstanceLine = renderCompactInstance(instanceData);
|
|
498
503
|
// Discovery & exploration stance. Guarded by tool availability: each
|
|
499
504
|
// line only appears when its tools exist; the stance paragraph is
|
|
500
505
|
// unconditional. Placed after guidelines, before tools — a stance, not
|
|
@@ -1,14 +1,26 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* Instance Composition: renders the
|
|
3
|
-
*
|
|
4
|
-
*
|
|
5
|
-
*
|
|
6
|
-
*
|
|
7
|
-
* the
|
|
8
|
-
*
|
|
9
|
-
*
|
|
10
|
-
*
|
|
11
|
-
*
|
|
2
|
+
* Instance Composition: two renders over the same gathered data.
|
|
3
|
+
*
|
|
4
|
+
* renderInstance is the full block (versions, runtime paths, OS/PID,
|
|
5
|
+
* session stats, extension packages, other pi instances) served on demand by
|
|
6
|
+
* the system_info tool. renderCompactInstance is the one-line orientation in
|
|
7
|
+
* the system prompt (braid version + install root, model, PID, session id,
|
|
8
|
+
* resource counts).
|
|
9
|
+
*
|
|
10
|
+
* Volatility rule: the system prompt is a cached prefix, so the compact line
|
|
11
|
+
* may carry only process-stable facts. A timestamp, elapsed time, turn count,
|
|
12
|
+
* tool average or context size would rewrite the prefix on every request and
|
|
13
|
+
* cost more than the field is worth; those facts stay in the system_info
|
|
14
|
+
* tool, which is a fresh turn by construction.
|
|
15
|
+
*
|
|
16
|
+
* Invariants: "Core" = pi-core's npm package folder, "braid root" = the
|
|
17
|
+
* loaded pi-braid package folder; packages come from the settings `packages`
|
|
18
|
+
* field (project / user-global, pi-core precedence), never a sibling walk;
|
|
19
|
+
* the pi-core version is pi-core's own `VERSION` export (the library braid is
|
|
20
|
+
* loaded into names the core that is running), with a filesystem walk as the
|
|
21
|
+
* fallback and as the source of the binary/package-folder fields; skills+memory
|
|
22
|
+
* live in memory-section.ts / the list_skills tool; output never contains
|
|
23
|
+
* internal module paths or "->".
|
|
12
24
|
*/
|
|
13
25
|
|
|
14
26
|
import { execSync, spawnSync } from "node:child_process";
|
|
@@ -16,7 +28,7 @@ import { readFileSync, existsSync, realpathSync } from "node:fs";
|
|
|
16
28
|
import { dirname, join } from "node:path";
|
|
17
29
|
import { fileURLToPath } from "node:url";
|
|
18
30
|
import * as os from "node:os";
|
|
19
|
-
import { getAgentDir } from "@earendil-works/pi-coding-agent";
|
|
31
|
+
import { getAgentDir, VERSION as PI_CORE_VERSION } from "@earendil-works/pi-coding-agent";
|
|
20
32
|
import type { PromptSection } from "./section.js";
|
|
21
33
|
import { discoverTopLevelExtensions, type TopLevelExtension } from "./top-level-extensions.js";
|
|
22
34
|
import { gatherL1Environment, type L1EnvironmentData } from "../agent-environment/index.js";
|
|
@@ -33,13 +45,43 @@ export interface SkillEntry {
|
|
|
33
45
|
}
|
|
34
46
|
|
|
35
47
|
interface PiVersionInfo {
|
|
48
|
+
/** The running library's own `VERSION`; the package.json version found by
|
|
49
|
+
* the walk only when that export is unavailable. */
|
|
36
50
|
version: string;
|
|
37
51
|
root: string;
|
|
38
52
|
/** Path to the resolved `pi` binary. */
|
|
39
53
|
binary: string;
|
|
40
54
|
}
|
|
41
55
|
|
|
56
|
+
/**
|
|
57
|
+
* The pi-core version of the library braid is loaded into, read from pi-core's
|
|
58
|
+
* own `VERSION` export.
|
|
59
|
+
*
|
|
60
|
+
* Braid is loaded by the harness, so that constant names the core actually
|
|
61
|
+
* running. A filesystem walk cannot answer the same question: the managed
|
|
62
|
+
* install keeps the entrypoint as a regular shell shim at `bin/pi` (so
|
|
63
|
+
* `realpathSync` changes nothing) and the package in a sibling
|
|
64
|
+
* `install/releases/<version>/node_modules` subtree, which no ancestor of
|
|
65
|
+
* `bin/` contains. Null when the export is absent or is not a version, so the
|
|
66
|
+
* caller falls back to the walk.
|
|
67
|
+
*/
|
|
68
|
+
function piCoreVersionFromLibrary(): string | null {
|
|
69
|
+
const value = typeof PI_CORE_VERSION === "string" ? PI_CORE_VERSION.trim() : "";
|
|
70
|
+
return /^\d+\.\d+\.\d+/.test(value) ? value : null;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/** The pi-core the current process is running over: the library's `VERSION`
|
|
74
|
+
* for the version, the filesystem walk for the binary and package folder. */
|
|
42
75
|
function discoverRunningPi(): PiVersionInfo {
|
|
76
|
+
const located = locateRunningPi();
|
|
77
|
+
const libraryVersion = piCoreVersionFromLibrary();
|
|
78
|
+
return libraryVersion ? { ...located, version: libraryVersion } : located;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/** Walk PATH and the filesystem for the running pi binary and its package
|
|
82
|
+
* folder. Supplies `root` and `binary`, and a version only as the fallback
|
|
83
|
+
* for a runtime where pi-core's `VERSION` export is missing. */
|
|
84
|
+
function locateRunningPi(): PiVersionInfo {
|
|
43
85
|
// 1. Find the actually-running `pi` binary. We DON'T just call
|
|
44
86
|
// `which pi` because that follows PATH order and can return a
|
|
45
87
|
// stale binary from a sibling repo's `node_modules/.bin` (e.g.
|
|
@@ -175,7 +217,10 @@ function readBraidVersion(): { version: string; root: string } {
|
|
|
175
217
|
} catch {
|
|
176
218
|
// fall through
|
|
177
219
|
}
|
|
178
|
-
|
|
220
|
+
// No cwd fallback: the compact line renders this path as the braid root,
|
|
221
|
+
// and a cwd there would read as a real install while duplicating the
|
|
222
|
+
// pi-injected <cwd>. An unresolved root is the honest value.
|
|
223
|
+
return { version: "unknown", root: "" };
|
|
179
224
|
}
|
|
180
225
|
|
|
181
226
|
// Discovers all `pi` processes running on the system (including the current
|
|
@@ -328,8 +373,14 @@ export interface InstanceContext {
|
|
|
328
373
|
/** Exported for system-info-tool — the full Instance data shape. */
|
|
329
374
|
export interface InstanceData {
|
|
330
375
|
braidVersion: string;
|
|
376
|
+
/** Folder of the running pi-braid package (where the loaded build lives).
|
|
377
|
+
* Empty when resolution failed. */
|
|
378
|
+
braidRoot: string;
|
|
331
379
|
/** Resolved pi-core info (version + npm package folder). */
|
|
332
380
|
pi: PiVersionInfo;
|
|
381
|
+
/** Session model as pi sees it (provider + model id); null when the
|
|
382
|
+
* runtime has no model selected. */
|
|
383
|
+
model: { provider: string; id: string } | null;
|
|
333
384
|
/** Userland pi settings directory (~/.pi/agent or
|
|
334
385
|
* PI_CODING_AGENT_DIR override). The agent uses this to find
|
|
335
386
|
* its own settings, skills, memory, and session files. */
|
|
@@ -371,7 +422,7 @@ export async function gatherInstanceData(
|
|
|
371
422
|
instanceCtx: InstanceContext,
|
|
372
423
|
): Promise<InstanceData> {
|
|
373
424
|
const pi = discoverRunningPi();
|
|
374
|
-
const
|
|
425
|
+
const { version: braidVersion, root: braidRoot } = readBraidVersion();
|
|
375
426
|
const session = gatherL1Environment(_pi, ctx);
|
|
376
427
|
const topLevelExtensions = discoverTopLevelExtensions();
|
|
377
428
|
const osInfo = {
|
|
@@ -388,8 +439,10 @@ export async function gatherInstanceData(
|
|
|
388
439
|
};
|
|
389
440
|
const otherPiInstances = discoverOtherPiInstances();
|
|
390
441
|
return {
|
|
391
|
-
braidVersion
|
|
442
|
+
braidVersion,
|
|
443
|
+
braidRoot,
|
|
392
444
|
pi,
|
|
445
|
+
model: ctx.model ? { provider: String(ctx.model.provider), id: ctx.model.id } : null,
|
|
393
446
|
settingsDir: getAgentDir(),
|
|
394
447
|
os: osInfo,
|
|
395
448
|
cwd: process.cwd(),
|
|
@@ -418,6 +471,37 @@ export async function instanceSection(
|
|
|
418
471
|
};
|
|
419
472
|
}
|
|
420
473
|
|
|
474
|
+
/**
|
|
475
|
+
* The compact Instance line for the system prompt.
|
|
476
|
+
*
|
|
477
|
+
* One field per question the agent would otherwise spend a tool call on:
|
|
478
|
+
*
|
|
479
|
+
* Agent which braid and pi-core build is answering?
|
|
480
|
+
* Root which pi-braid folder is loaded (stale local install vs global)?
|
|
481
|
+
* Model which provider/model will the next request go to?
|
|
482
|
+
* PID which OS process is this session, for ps/lock checks?
|
|
483
|
+
* Session which session file holds this transcript?
|
|
484
|
+
* Resources did the skill pack and memory stores load at all?
|
|
485
|
+
*
|
|
486
|
+
* A field answering only "nice to know" does not belong here, and neither
|
|
487
|
+
* does anything volatile: see the volatility rule in the module docstring.
|
|
488
|
+
* The block is process-stable by construction, so it renders byte-identical
|
|
489
|
+
* on every turn and the provider prefix cache holds across the session.
|
|
490
|
+
*/
|
|
491
|
+
export function renderCompactInstance(d: InstanceData): string {
|
|
492
|
+
const model = d.model ? `${d.model.provider}/${d.model.id}` : "(unset)";
|
|
493
|
+
const skills = `${d.skillCount} skill${d.skillCount === 1 ? "" : "s"}`;
|
|
494
|
+
const memories = `${d.memoryCount} memor${d.memoryCount === 1 ? "y" : "ies"}`;
|
|
495
|
+
return [
|
|
496
|
+
`Agent: Braid v${d.braidVersion} (over pi-core v${d.pi.version})`,
|
|
497
|
+
`Root: ${d.braidRoot || "(unknown)"}`,
|
|
498
|
+
`Model: ${model}`,
|
|
499
|
+
`PID: ${d.session.pid}`,
|
|
500
|
+
`Session: ${d.sessionId || "(unknown)"}`,
|
|
501
|
+
`Resources: ${skills}, ${memories}`,
|
|
502
|
+
].join(" | ");
|
|
503
|
+
}
|
|
504
|
+
|
|
421
505
|
/** Exported for system-info-tool — renders InstanceData to plain text. */
|
|
422
506
|
export async function renderInstance(d: InstanceData): Promise<string> {
|
|
423
507
|
const lines: string[] = [];
|
|
@@ -3,9 +3,9 @@
|
|
|
3
3
|
*
|
|
4
4
|
* Extracts the Instance section (Agent version, pi-core version, paths,
|
|
5
5
|
* OS, session stats, extensions, other instances) from the system prompt
|
|
6
|
-
* into a read-on-demand tool. The prompt keeps only
|
|
7
|
-
* orientation (
|
|
8
|
-
* block lives here.
|
|
6
|
+
* into a read-on-demand tool. The prompt keeps only the compact one-line
|
|
7
|
+
* orientation (build + install root, model, PID, session, resource counts)
|
|
8
|
+
* at the bottom; the full Instance block lives here.
|
|
9
9
|
*
|
|
10
10
|
* This saves ~60-100+ tokens per prompt turn while keeping the data
|
|
11
11
|
* available when the agent actually needs it.
|
|
@@ -96,7 +96,7 @@ export const TOOL_GUIDELINES: Record<string, string> = {
|
|
|
96
96
|
|
|
97
97
|
// ── skills-tool (default-enabled) ──
|
|
98
98
|
list_skills:
|
|
99
|
-
"when: entering a domain that may have a skill; when-not: after the skill is loaded; args: page/pageSize; caveat: read the WHOLE SKILL.md before acting in the domain",
|
|
99
|
+
"when: entering a domain that may have a skill; when-not: after the skill is loaded; args: page/pageSize/sectionsMax/rank; caveat: rows arrive ordered by relevance to the current task (rows with evidence carry relevance {score, reason}; the response carries ranking {tier, basis, policy}; rank: catalog for the plain order) and reach (reachable, lines, bytes, chars, estTokens, sectionCount, sections) prices the read — read the WHOLE SKILL.md before acting in the domain",
|
|
100
100
|
skill_stats:
|
|
101
101
|
"when: measure skill adoption — suggested vs loaded counters; args: none; caveat: session + all-time counters (durable, skills-usage.json)",
|
|
102
102
|
|
|
@@ -15,11 +15,15 @@
|
|
|
15
15
|
* a signal: it fires broad skills on almost any prompt.
|
|
16
16
|
* Keywords are stemmed with one suffix rule (trailing s/es) so plural
|
|
17
17
|
* prompts hit singular name tokens ("skills" → "skill").
|
|
18
|
-
* Corpus-common words are gated out of the weak legs
|
|
19
|
-
*
|
|
20
|
-
*
|
|
21
|
-
*
|
|
22
|
-
*
|
|
18
|
+
* Corpus-common words are gated out of the weak legs AND out of the
|
|
19
|
+
* name leg's prefix hits: a word present in COMMON_KEYWORD_DF or more of
|
|
20
|
+
* the cached skills' documents cannot tell skills apart, so
|
|
21
|
+
* description/path hits from it score nothing. A name hit is word-shaped
|
|
22
|
+
* by construction — a whole name token, or the start of one — so a word
|
|
23
|
+
* buried inside a coined token ("line" in placement-disc**line**) is not
|
|
24
|
+
* a name hit at all. A whole-name-token hit and a trigger hit are never
|
|
25
|
+
* gated: the skill's own identity vocabulary is what a prompt naming it
|
|
26
|
+
* looks like, and a curated phrase is the author's signal.
|
|
23
27
|
* 1b. Ranking: equal scores compare by more distinct matched signals, then
|
|
24
28
|
* by rarer evidence (lower summed document frequency), then by name.
|
|
25
29
|
* Alphabetical order alone decided which of two equally-scored skills
|
|
@@ -109,6 +113,7 @@ import {
|
|
|
109
113
|
recordSessionStart,
|
|
110
114
|
} from "./session-records.js";
|
|
111
115
|
import { triggerMatches } from "./skill-triggers.js";
|
|
116
|
+
import type { TriggerSource } from "./skill-triggers.js";
|
|
112
117
|
|
|
113
118
|
const log = createLogger("skills-auto-inject");
|
|
114
119
|
|
|
@@ -159,7 +164,8 @@ export const MIN_NON_NAME_SCORE = 2;
|
|
|
159
164
|
* A keyword present in this many skill documents or more is corpus-common: it
|
|
160
165
|
* appears in a large share of the catalog (5 of 22 skills = 23%), so it cannot
|
|
161
166
|
* distinguish one skill from another and contributes NOTHING to the weak legs
|
|
162
|
-
* (description, catalog path)
|
|
167
|
+
* (description, catalog path) — or to the name leg's token-prefix rule, the one
|
|
168
|
+
* name hit that can rest on a shared word.
|
|
163
169
|
*
|
|
164
170
|
* The number is measured, not guessed. Two measurements, one threshold:
|
|
165
171
|
*
|
|
@@ -286,6 +292,8 @@ export interface CachedSkill {
|
|
|
286
292
|
disableModelInvocation?: boolean;
|
|
287
293
|
/** Frontmatter trigger phrases (setCachedSkills resolves them from SKILL.md). */
|
|
288
294
|
triggers?: string[];
|
|
295
|
+
/** Which source authored each phrase (the row's evidence label). */
|
|
296
|
+
triggerSources?: Record<string, TriggerSource>;
|
|
289
297
|
}
|
|
290
298
|
|
|
291
299
|
// Shared module-level variable rather than a per-module copy: the import
|
|
@@ -377,16 +385,56 @@ export interface SkillMatch {
|
|
|
377
385
|
signals: number;
|
|
378
386
|
/** Summed document frequency of the matched keywords — lower is rarer. */
|
|
379
387
|
evidenceDf: number;
|
|
388
|
+
/** Strongest evidence behind the score; null when the skill did not qualify. */
|
|
389
|
+
reason: RelevanceReason | null;
|
|
380
390
|
}
|
|
381
391
|
|
|
382
|
-
|
|
392
|
+
/**
|
|
393
|
+
* What the strongest evidence for a row was. Short on purpose: a ranking row
|
|
394
|
+
* says "trigger", not a sentence — the reader is choosing a read, not reading
|
|
395
|
+
* an explanation.
|
|
396
|
+
*
|
|
397
|
+
* trigger — an authored phrase from frontmatter or the description tail
|
|
398
|
+
* heading — an authored phrase from a `## trigger:` body heading
|
|
399
|
+
* name — a keyword in the skill's own name
|
|
400
|
+
* description — a description or catalog-path keyword (the weak legs)
|
|
401
|
+
*/
|
|
402
|
+
export type RelevanceReason = "trigger" | "heading" | "name" | "description";
|
|
403
|
+
|
|
404
|
+
/** Evidence strength for the row's single `reason` field. */
|
|
405
|
+
const REASON_STRENGTH: Record<RelevanceReason, number> = {
|
|
406
|
+
trigger: 4,
|
|
407
|
+
heading: 3,
|
|
408
|
+
name: 2,
|
|
409
|
+
description: 1,
|
|
410
|
+
};
|
|
411
|
+
|
|
412
|
+
/**
|
|
413
|
+
* How a keyword occurs in a skill name: as a whole token, as the start of a
|
|
414
|
+
* longer token, or not at all.
|
|
415
|
+
*
|
|
416
|
+
* The third answer is the fix: the name leg used to award points to any
|
|
417
|
+
* substring anywhere in the name, so a corpus-common word ("line", df 7 of 22)
|
|
418
|
+
* scored +2 for placement-disc**line** and release-pi**peline** and carried the
|
|
419
|
+
* name-hit exemption from the qualification bar with it. A word buried inside
|
|
420
|
+
* a coined token names the author's coinage, not the prompt's subject; a word
|
|
421
|
+
* that starts a token still reads as the author's own vocabulary ("engine" in
|
|
422
|
+
* software-engineer).
|
|
423
|
+
*/
|
|
424
|
+
function nameOccurrence(tokens: string[], kw: string): "token" | "prefix" | null {
|
|
425
|
+
if (tokens.includes(kw)) return "token";
|
|
426
|
+
for (const token of tokens) if (token.length > kw.length && token.startsWith(kw)) return "prefix";
|
|
427
|
+
return null;
|
|
428
|
+
}
|
|
429
|
+
|
|
430
|
+
const NO_MATCH: SkillMatch = { score: 0, signals: 0, evidenceDf: 0, reason: null };
|
|
383
431
|
|
|
384
432
|
/**
|
|
385
433
|
* Score a skill against a set of keywords.
|
|
386
434
|
*
|
|
387
435
|
* Scoring rules:
|
|
388
|
-
* +3 skill name
|
|
389
|
-
* +2 skill name
|
|
436
|
+
* +3 skill name carries a keyword as a whole token (exact match)
|
|
437
|
+
* +2 skill name starts a token with a keyword, below the frequency gate
|
|
390
438
|
* +2 a trigger phrase occurs in the prompt (word-bounded)
|
|
391
439
|
* +1 skill description contains a keyword
|
|
392
440
|
* +1 the skill's own catalog path contains a keyword (e.g. "research" in
|
|
@@ -397,8 +445,11 @@ const NO_MATCH: SkillMatch = { score: 0, signals: 0, evidenceDf: 0 };
|
|
|
397
445
|
*
|
|
398
446
|
* `keywordDf` is the corpus document frequency of the prompt's keywords (see
|
|
399
447
|
* corpusKeywordFrequency). A keyword at COMMON_KEYWORD_DF or above scores
|
|
400
|
-
* nothing on the weak legs
|
|
401
|
-
*
|
|
448
|
+
* nothing on the weak legs, and nothing on the name leg's token-prefix rule:
|
|
449
|
+
* a common word that only starts a token ("line" in "line-counting") is
|
|
450
|
+
* vocabulary the catalog shares, not the skill's own. Passing no map scores
|
|
451
|
+
* every keyword at full weight (the pre-rarity behavior, which the unit
|
|
452
|
+
* fixtures pin).
|
|
402
453
|
*
|
|
403
454
|
* Qualification bar: a skill whose match never touches its NAME (description
|
|
404
455
|
* and/or filePath hits only) must reach a total score of at least
|
|
@@ -421,7 +472,12 @@ export function matchSkill(
|
|
|
421
472
|
let signals = 0;
|
|
422
473
|
let evidenceDf = 0;
|
|
423
474
|
let nameHit = false;
|
|
475
|
+
let reason: RelevanceReason | null = null;
|
|
476
|
+
const noteReason = (candidate: RelevanceReason) => {
|
|
477
|
+
if (!reason || REASON_STRENGTH[candidate] > REASON_STRENGTH[reason]) reason = candidate;
|
|
478
|
+
};
|
|
424
479
|
const name = skill.name.toLowerCase();
|
|
480
|
+
const nameTokens = name.split(/[^a-z0-9]+/).filter(Boolean);
|
|
425
481
|
const desc = skill.description.toLowerCase();
|
|
426
482
|
const path = skill.filePath.toLowerCase().split(/[\\/]/).filter(Boolean).slice(-2).join("/");
|
|
427
483
|
const dfOf = (kw: string) => keywordDf?.get(kw) ?? 0;
|
|
@@ -431,26 +487,32 @@ export function matchSkill(
|
|
|
431
487
|
score += 2;
|
|
432
488
|
signals++;
|
|
433
489
|
nameHit = true;
|
|
434
|
-
// A curated phrase is the rarest evidence a skill can offer: df 0.
|
|
490
|
+
// A curated phrase is the rarest evidence a skill can offer: df 0. Its
|
|
491
|
+
// provenance is what the row reports as its evidence label.
|
|
492
|
+
noteReason(skill.triggerSources?.[trig] === "heading" ? "heading" : "trigger");
|
|
435
493
|
}
|
|
436
494
|
}
|
|
437
495
|
|
|
438
496
|
for (const kw of keywords) {
|
|
439
497
|
const df = dfOf(kw);
|
|
440
|
-
|
|
441
|
-
|
|
498
|
+
const occurrence = nameOccurrence(nameTokens, kw);
|
|
499
|
+
// Exact token match in name: the skill's own identity vocabulary, never gated.
|
|
500
|
+
if (occurrence === "token") {
|
|
442
501
|
score += 3;
|
|
443
502
|
signals++;
|
|
444
503
|
nameHit = true;
|
|
445
504
|
evidenceDf += df;
|
|
505
|
+
noteReason("name");
|
|
446
506
|
continue;
|
|
447
507
|
}
|
|
448
|
-
//
|
|
449
|
-
|
|
508
|
+
// Token-prefix match in name ("engine" in "software-engineer"): name
|
|
509
|
+
// evidence, but only while the word is distinctive enough to mean it.
|
|
510
|
+
if (occurrence === "prefix" && df < COMMON_KEYWORD_DF) {
|
|
450
511
|
score += 2;
|
|
451
512
|
signals++;
|
|
452
513
|
nameHit = true;
|
|
453
514
|
evidenceDf += df;
|
|
515
|
+
noteReason("name");
|
|
454
516
|
continue;
|
|
455
517
|
}
|
|
456
518
|
// Corpus-common keyword: the weak legs score nothing for it, so a prompt
|
|
@@ -471,11 +533,12 @@ export function matchSkill(
|
|
|
471
533
|
if (weakHit) {
|
|
472
534
|
signals++;
|
|
473
535
|
evidenceDf += df;
|
|
536
|
+
noteReason("description");
|
|
474
537
|
}
|
|
475
538
|
}
|
|
476
539
|
|
|
477
540
|
if (!nameHit && score < MIN_NON_NAME_SCORE) return NO_MATCH;
|
|
478
|
-
return { score, signals, evidenceDf };
|
|
541
|
+
return { score, signals, evidenceDf, reason };
|
|
479
542
|
}
|
|
480
543
|
|
|
481
544
|
/** The score alone (see matchSkill for the rules and the rarity gate). */
|
|
@@ -500,8 +563,23 @@ export interface ScoredSkill {
|
|
|
500
563
|
evidenceDf?: number;
|
|
501
564
|
}
|
|
502
565
|
|
|
566
|
+
/**
|
|
567
|
+
* The ranking comparator, shared by the whisper's selection and the catalog
|
|
568
|
+
* read: score, then breadth of match (distinct signals), then rarity of the
|
|
569
|
+
* evidence (summed document frequency), then name. Pure.
|
|
570
|
+
*/
|
|
571
|
+
function compareScored(a: ScoredSkill, b: ScoredSkill): number {
|
|
572
|
+
return (
|
|
573
|
+
b.score - a.score ||
|
|
574
|
+
(b.signals ?? 0) - (a.signals ?? 0) ||
|
|
575
|
+
(a.evidenceDf ?? 0) - (b.evidenceDf ?? 0) ||
|
|
576
|
+
a.skill.name.localeCompare(b.skill.name)
|
|
577
|
+
);
|
|
578
|
+
}
|
|
579
|
+
|
|
503
580
|
/**
|
|
504
581
|
* Decide which scored skills to suggest given the session injection state.
|
|
582
|
+
*
|
|
505
583
|
* Pure — mirrors the handler's decision path so it can be unit-tested:
|
|
506
584
|
* sort (score desc, distinct signals desc, evidence df asc, name asc) →
|
|
507
585
|
* cooldown filter (global floor + per-skill loaded extension) → slot budget
|
|
@@ -523,13 +601,7 @@ export function selectSuggestions(
|
|
|
523
601
|
): ScoredSkill[] {
|
|
524
602
|
if (!scored.length) return [];
|
|
525
603
|
|
|
526
|
-
const sorted = [...scored].sort(
|
|
527
|
-
(a, b) =>
|
|
528
|
-
b.score - a.score ||
|
|
529
|
-
(b.signals ?? 0) - (a.signals ?? 0) ||
|
|
530
|
-
(a.evidenceDf ?? 0) - (b.evidenceDf ?? 0) ||
|
|
531
|
-
a.skill.name.localeCompare(b.skill.name),
|
|
532
|
-
);
|
|
604
|
+
const sorted = [...scored].sort(compareScored);
|
|
533
605
|
|
|
534
606
|
const available = sorted.filter((s) => !onCooldown(s.skill.name, injected, currentTurn));
|
|
535
607
|
if (!available.length) return [];
|
|
@@ -543,6 +615,106 @@ export function selectSuggestions(
|
|
|
543
615
|
return available.slice(0, slotBudget);
|
|
544
616
|
}
|
|
545
617
|
|
|
618
|
+
// Deterministic ranking for the catalog read
|
|
619
|
+
|
|
620
|
+
/**
|
|
621
|
+
* Declared margin: a gap smaller than this between the first and second
|
|
622
|
+
* qualified skill means the top is a coin flip, and the read says so
|
|
623
|
+
* (`thin-margin`) instead of presenting the order as a decision. The number is
|
|
624
|
+
* deliberate, not measured: one description keyword (+1) is exactly the
|
|
625
|
+
* distance the scorer says is too weak to qualify a skill on its own
|
|
626
|
+
* (MIN_NON_NAME_SCORE), so a lead that one extra weak hit could erase is not a
|
|
627
|
+
* lead.
|
|
628
|
+
*/
|
|
629
|
+
export const RANK_MARGIN_THRESHOLD = 2;
|
|
630
|
+
|
|
631
|
+
/**
|
|
632
|
+
* A task text shorter than this cannot carry a ranking signal: a greeting or a
|
|
633
|
+
* two-word nudge names no domain, so the deterministic tier reports itself
|
|
634
|
+
* short rather than confidently wrong.
|
|
635
|
+
*/
|
|
636
|
+
export const RANK_SHORT_TASK_CHARS = 24;
|
|
637
|
+
|
|
638
|
+
/** Why the deterministic tier answered the way it did. */
|
|
639
|
+
export type RankingBasis =
|
|
640
|
+
| "no-task"
|
|
641
|
+
| "short-task"
|
|
642
|
+
| "no-score"
|
|
643
|
+
| "unambiguous"
|
|
644
|
+
| "tie"
|
|
645
|
+
| "thin-margin";
|
|
646
|
+
|
|
647
|
+
/** One skill as the ranking read consumes it: match evidence plus its label. */
|
|
648
|
+
export interface RankedSkill {
|
|
649
|
+
skill: CachedSkill;
|
|
650
|
+
score: number;
|
|
651
|
+
signals: number;
|
|
652
|
+
evidenceDf: number;
|
|
653
|
+
reason: RelevanceReason | null;
|
|
654
|
+
}
|
|
655
|
+
|
|
656
|
+
/** The deterministic tier's whole answer: an ordered list and a verdict on it. */
|
|
657
|
+
export interface DeterministicRanking {
|
|
658
|
+
/** Qualified skills only, best first (the order the whisper ranks by). */
|
|
659
|
+
ranked: RankedSkill[];
|
|
660
|
+
/** True when the list cannot separate its own top — the escalation trigger. */
|
|
661
|
+
ambiguous: boolean;
|
|
662
|
+
basis: RankingBasis;
|
|
663
|
+
}
|
|
664
|
+
|
|
665
|
+
/**
|
|
666
|
+
* Rank the catalog against a task text without a model. Pure given the cache.
|
|
667
|
+
*
|
|
668
|
+
* Ordering is the whisper's comparator (score, then distinct signals, then
|
|
669
|
+
* summed evidence df, then name) so the two surfaces can never disagree about
|
|
670
|
+
* which skill is better. `ambiguous` is the one thing the whisper does not
|
|
671
|
+
* need: it decides every turn with slots and cooldowns, while a catalog read
|
|
672
|
+
* shows the whole list and therefore must say when its own top is not decided
|
|
673
|
+
* (a tie or a thin margin) or when the task text could not inform it at all.
|
|
674
|
+
*
|
|
675
|
+
* The verdict:
|
|
676
|
+
* no-task — no task text at all; nothing to rank.
|
|
677
|
+
* short-task — the text carries no significant keyword, or is shorter than
|
|
678
|
+
* RANK_SHORT_TASK_CHARS: nothing here can rank a catalog.
|
|
679
|
+
* no-score — every skill scored zero: unambiguous (nothing applies).
|
|
680
|
+
* tie — the top two score the same: ambiguous.
|
|
681
|
+
* thin-margin — the top two sit closer than RANK_MARGIN_THRESHOLD: ambiguous.
|
|
682
|
+
* unambiguous — one skill leads the field by at least the margin.
|
|
683
|
+
*/
|
|
684
|
+
export function rankSkillsDeterministic(
|
|
685
|
+
skills: CachedSkill[],
|
|
686
|
+
taskText: string,
|
|
687
|
+
): DeterministicRanking {
|
|
688
|
+
const text = (taskText ?? "").trim();
|
|
689
|
+
if (!text) return { ranked: [], ambiguous: false, basis: "no-task" };
|
|
690
|
+
const keywords = extractKeywords(text);
|
|
691
|
+
const ranked: RankedSkill[] = [];
|
|
692
|
+
if (keywords.length) {
|
|
693
|
+
const keywordDf = corpusKeywordFrequency(keywords, skills);
|
|
694
|
+
for (const skill of skills) {
|
|
695
|
+
const match = matchSkill(skill, keywords, text, keywordDf);
|
|
696
|
+
if (match.score <= 0) continue;
|
|
697
|
+
ranked.push({
|
|
698
|
+
skill,
|
|
699
|
+
score: match.score,
|
|
700
|
+
signals: match.signals,
|
|
701
|
+
evidenceDf: match.evidenceDf,
|
|
702
|
+
reason: match.reason,
|
|
703
|
+
});
|
|
704
|
+
}
|
|
705
|
+
}
|
|
706
|
+
ranked.sort(compareScored);
|
|
707
|
+
if (text.length < RANK_SHORT_TASK_CHARS || !keywords.length) {
|
|
708
|
+
return { ranked, ambiguous: true, basis: "short-task" };
|
|
709
|
+
}
|
|
710
|
+
if (!ranked.length) return { ranked, ambiguous: false, basis: "no-score" };
|
|
711
|
+
if (ranked.length === 1) return { ranked, ambiguous: false, basis: "unambiguous" };
|
|
712
|
+
const margin = ranked[0].score - ranked[1].score;
|
|
713
|
+
if (margin === 0) return { ranked, ambiguous: true, basis: "tie" };
|
|
714
|
+
if (margin < RANK_MARGIN_THRESHOLD) return { ranked, ambiguous: true, basis: "thin-margin" };
|
|
715
|
+
return { ranked, ambiguous: false, basis: "unambiguous" };
|
|
716
|
+
}
|
|
717
|
+
|
|
546
718
|
/**
|
|
547
719
|
* Cooldown gate: the global floor applies to every injection; a skill that
|
|
548
720
|
* was loaded after its injection additionally cools down for
|