Q19: pack the skills most relevant to the task first

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
ZacharyZhang-NYandClaude Opus 5.5 committed 2026-10-08 04:48:44 -04:00
1 parent d79fd87077
commit b32e784469
9 files changed
+194 -111

No files matched your search

+25
View File
@@ -0,0 +1,25 @@
const LATIN_WORD = /[a-z0-9]{3,}/g;
const CJK_RUN = /[\u3400-\u9fff]+/g;
/** Words (latin, 3+ chars) and character pairs (CJK) of a text. */
function terms(text: string): Set<string> {
const lower = text.toLowerCase();
const found = new Set(lower.match(LATIN_WORD) ?? []);
for (const run of lower.match(CJK_RUN) ?? []) {
for (let index = 0; index < run.length - 1; index += 1) found.add(run.slice(index, index + 2));
}
return found;
}
/** Orders items by how many terms they share with the task; ties keep their order. */
export function orderByRelevance<T>(items: T[], describe: (item: T) => string, taskText: string): T[] {
const taskTerms = terms(taskText);
return items
.map((item, index) => {
let score = 0;
for (const term of terms(describe(item))) if (taskTerms.has(term)) score += 1;
return { item, index, score };
})
.sort((a, b) => b.score - a.score || a.index - b.index)
.map((entry) => entry.item);
}
+9 -99
View File
@@ -1,7 +1,4 @@
import { estimateTokens } from "./context-budget";
import { existsSync, readFileSync } from "node:fs";
import { createHash } from "node:crypto";
import { normalize } from "node:path";
import type { DatabaseSync } from "node:sqlite";
import type { BindSkillInput, ImportSkillDirectoryInput, ResolveAgentSkillsInput, RunSkillTestsInput } from "../../shared/commands";
import { SLO_SIGNAL_KEY } from "../../shared/domain";
@@ -10,6 +7,9 @@ import { AuditService } from "./audit-service";
import { OperationsService } from "./operations-service";
import { copySkillRevision, recursiveSkillChecksum } from "./skill-artifacts";
import { loadSkillManifest, type SkillManifest } from "./skill-manifest";
import { orderByRelevance } from "./skill-relevance";
import { runManifestArtifactTest, verifyRevisionStructure, type SkillArtifactRow, type SkillTestRow } from "./skill-tests";
import { estimateTokens } from "./context-budget";
function slugify(value: string): string {
return value.trim().toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "");
@@ -236,7 +236,7 @@ export class SkillService {
/**
* Freezes the exact skill set this run carries: forced house-style skills
* first (identical for everyone, CEO included), then the agent's enabled
* bindings in priority order, deduplicated per skill. Skills pack whole
* bindings, most relevant to the task first, deduplicated per skill. Skills pack whole
* until input.maxTokens; whatever does not fit is named in the compiled
* prompt instead of silently overflowing the model's context.
*/
@@ -263,7 +263,11 @@ export class SkillService {
`).all(input.orgId, input.agentId) as unknown as RuntimeSkillRow[];
const rows: RuntimeSkillRow[] = [];
const seenSkillIds = new Set<string>();
for (const row of [...forcedRows, ...boundRows]) {
const relevantBound = orderByRelevance(boundRows, (row) => {
const manifest = JSON.parse(row.manifest_json) as SkillManifest;
return `${manifest.name} ${manifest.description ?? ""}`;
}, input.taskText);
for (const row of [...forcedRows, ...relevantBound]) {
if (seenSkillIds.has(row.skill_id)) continue;
seenSkillIds.add(row.skill_id);
rows.push(row);
@@ -414,97 +418,3 @@ interface SkillRevisionTestRow {
version_semver: string;
slug: string;
}
interface SkillTestRow {
id: string;
test_type: string;
expected_output_ref: string;
}
interface SkillArtifactRow {
artifact_type: string;
object_key: string;
sha256: string;
size_bytes: number;
}
interface SkillTestResult {
status: "passed" | "failed";
testType: string;
expectedOutputRef: string;
checks: Array<{ name: string; status: "passed" | "failed"; detail: string }>;
artifactSha256?: string;
failure?: string;
}
function verifyRevisionStructure(artifacts: SkillArtifactRow[]): SkillTestResult | null {
const requiredTypes = ["manifest", "entrypoint"];
for (const type of requiredTypes) {
if (!artifacts.some((artifact) => artifact.artifact_type === type)) {
return failedSkillTest("revision_structure", type, `Skill revision artifact is missing: ${type}`);
}
}
for (const artifact of artifacts) {
try {
verifyArtifactIntegrity(artifact);
} catch (error) {
return failedSkillTest("artifact_integrity", artifact.object_key, error instanceof Error ? error.message : String(error));
}
}
return null;
}
function runManifestArtifactTest(test: SkillTestRow, artifacts: SkillArtifactRow[]): SkillTestResult {
if (test.test_type !== "manifest") {
return failedSkillTest(test.test_type, test.expected_output_ref, `Unsupported skill test type: ${test.test_type}`);
}
const testArtifact = artifacts.find((artifact) => (
artifact.artifact_type === "test" && artifactMatchesExpectedRef(artifact.object_key, test.expected_output_ref)
));
if (!testArtifact) return failedSkillTest(test.test_type, test.expected_output_ref, "Skill test artifact was not found.");
try {
const content = verifyArtifactIntegrity(testArtifact).toString("utf8");
if (!content.trim()) throw new Error("Skill test artifact is empty.");
return {
status: "passed",
testType: test.test_type,
expectedOutputRef: test.expected_output_ref,
artifactSha256: testArtifact.sha256,
checks: [
{ name: "manifest_test_artifact", status: "passed", detail: "Artifact exists, checksum matches, and content is non-empty." },
],
};
} catch (error) {
return failedSkillTest(test.test_type, test.expected_output_ref, error instanceof Error ? error.message : String(error));
}
}
function verifyArtifactIntegrity(artifact: SkillArtifactRow): Buffer {
if (!existsSync(artifact.object_key)) throw new Error(`Skill artifact is missing: ${artifact.object_key}`);
const body = readFileSync(artifact.object_key);
const sha256 = createHash("sha256").update(body).digest("hex");
if (sha256 !== artifact.sha256) throw new Error(`Skill artifact checksum mismatch: ${artifact.object_key}`);
if (body.byteLength !== artifact.size_bytes) throw new Error(`Skill artifact size mismatch: ${artifact.object_key}`);
return body;
}
function artifactMatchesExpectedRef(objectKey: string, expectedRef: string): boolean {
const expected = normalizeSkillPath(expectedRef);
const actual = normalizeSkillPath(objectKey);
return actual === expected || actual.endsWith(`/${expected}`);
}
function normalizeSkillPath(value: string): string {
return normalize(value).replaceAll("\\", "/");
}
function failedSkillTest(testType: string, expectedOutputRef: string, failure: string): SkillTestResult {
return {
status: "failed",
testType,
expectedOutputRef,
checks: [{ name: "skill_test", status: "failed", detail: failure }],
failure,
};
}
+97
View File
@@ -0,0 +1,97 @@
import { createHash } from "node:crypto";
import { existsSync, readFileSync } from "node:fs";
import { normalize } from "node:path";
export interface SkillTestRow {
id: string;
test_type: string;
expected_output_ref: string;
}
export interface SkillArtifactRow {
artifact_type: string;
object_key: string;
sha256: string;
size_bytes: number;
}
export interface SkillTestResult {
status: "passed" | "failed";
testType: string;
expectedOutputRef: string;
checks: Array<{ name: string; status: "passed" | "failed"; detail: string }>;
artifactSha256?: string;
failure?: string;
}
export function verifyRevisionStructure(artifacts: SkillArtifactRow[]): SkillTestResult | null {
const requiredTypes = ["manifest", "entrypoint"];
for (const type of requiredTypes) {
if (!artifacts.some((artifact) => artifact.artifact_type === type)) {
return failedSkillTest("revision_structure", type, `Skill revision artifact is missing: ${type}`);
}
}
for (const artifact of artifacts) {
try {
verifyArtifactIntegrity(artifact);
} catch (error) {
return failedSkillTest("artifact_integrity", artifact.object_key, error instanceof Error ? error.message : String(error));
}
}
return null;
}
export function runManifestArtifactTest(test: SkillTestRow, artifacts: SkillArtifactRow[]): SkillTestResult {
if (test.test_type !== "manifest") {
return failedSkillTest(test.test_type, test.expected_output_ref, `Unsupported skill test type: ${test.test_type}`);
}
const testArtifact = artifacts.find((artifact) => (
artifact.artifact_type === "test" && artifactMatchesExpectedRef(artifact.object_key, test.expected_output_ref)
));
if (!testArtifact) return failedSkillTest(test.test_type, test.expected_output_ref, "Skill test artifact was not found.");
try {
const content = verifyArtifactIntegrity(testArtifact).toString("utf8");
if (!content.trim()) throw new Error("Skill test artifact is empty.");
return {
status: "passed",
testType: test.test_type,
expectedOutputRef: test.expected_output_ref,
artifactSha256: testArtifact.sha256,
checks: [
{ name: "manifest_test_artifact", status: "passed", detail: "Artifact exists, checksum matches, and content is non-empty." },
],
};
} catch (error) {
return failedSkillTest(test.test_type, test.expected_output_ref, error instanceof Error ? error.message : String(error));
}
}
function verifyArtifactIntegrity(artifact: SkillArtifactRow): Buffer {
if (!existsSync(artifact.object_key)) throw new Error(`Skill artifact is missing: ${artifact.object_key}`);
const body = readFileSync(artifact.object_key);
const sha256 = createHash("sha256").update(body).digest("hex");
if (sha256 !== artifact.sha256) throw new Error(`Skill artifact checksum mismatch: ${artifact.object_key}`);
if (body.byteLength !== artifact.size_bytes) throw new Error(`Skill artifact size mismatch: ${artifact.object_key}`);
return body;
}
function artifactMatchesExpectedRef(objectKey: string, expectedRef: string): boolean {
const expected = normalizeSkillPath(expectedRef);
const actual = normalizeSkillPath(objectKey);
return actual === expected || actual.endsWith(`/${expected}`);
}
function normalizeSkillPath(value: string): string {
return normalize(value).replaceAll("\\", "/");
}
function failedSkillTest(testType: string, expectedOutputRef: string, failure: string): SkillTestResult {
return {
status: "failed",
testType,
expectedOutputRef,
checks: [{ name: "skill_test", status: "failed", detail: failure }],
failure,
};
}
+3 -3
View File
@@ -156,7 +156,7 @@ export class TaskExecutionService {
let providerRequestId: string | null = null;
let skillRuntimeSnapshot: SkillRuntimeSnapshotRow | null = null;
try {
skillRuntimeSnapshot = this.resolveSkillRuntimeSnapshot(orgId, agent.id, runId, skillBudgetTokens(provider.context_window_tokens));
skillRuntimeSnapshot = this.resolveSkillRuntimeSnapshot(orgId, agent.id, runId, skillBudgetTokens(provider.context_window_tokens), `${task.title}\n${task.description}`);
// Watermark for reply delivery and mid-run message polling.
const runStartedAt = new Date().toISOString();
const chatContext = loadChatWakeContext(this.db, orgId, agent.id, isolation.secretScopeJson);
@@ -616,9 +616,9 @@ export class TaskExecutionService {
`).run(TASK_RUN_STATE.FAILED, providerRequestId, new Date().toISOString(), errorMessage, runId, orgId);
}
private resolveSkillRuntimeSnapshot(orgId: string, agentId: string, runId: string, maxTokens: number): SkillRuntimeSnapshotRow | null {
private resolveSkillRuntimeSnapshot(orgId: string, agentId: string, runId: string, maxTokens: number, taskText: string): SkillRuntimeSnapshotRow | null {
if (!this.skills.hasRuntimeSkills(orgId, agentId)) return null;
const snapshotId = this.skills.resolveRuntimeSnapshot({ orgId, agentId, runId, maxTokens });
const snapshotId = this.skills.resolveRuntimeSnapshot({ orgId, agentId, runId, maxTokens, taskText });
const snapshot = this.db.prepare(`
select id, compiled_prompt, tools_manifest, source_revision_ids
from skill_runtime_snapshots
+2
View File
@@ -21,6 +21,8 @@ export interface ResolveAgentSkillsInput {
runId: string;
/** Token budget for the compiled skills. */
maxTokens: number;
/** Task title and description, to rank bound skills by relevance. */
taskText: string;
}
export interface RunSkillTestsInput {