@amoree-code/ocean 2.14.0 → 2.16.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/dist/application/clients/hooks.js +16 -7
- package/dist/application/integrations/skill-auto-sync.js +8 -0
- package/dist/application/integrations/skill-filter.js +5 -3
- package/dist/application/integrations/skill-router.js +438 -0
- package/dist/application/upkeep/nightly-upkeep.js +1 -1
- package/dist/interfaces/cli/brief-command.js +1 -1
- package/dist/interfaces/cli/command-registry.js +70 -1
- package/dist/interfaces/cli/harvest-command.js +4 -3
- package/dist/interfaces/cli/help-command.js +4 -4
- package/dist/interfaces/cli/scorecard-command.js +1 -1
- package/dist/interfaces/cli/setup-command.js +20 -2
- package/node_modules/@ocean/brain/dist/memory/brain-dump.js +196 -26
- package/node_modules/@ocean/brain/dist/memory/routing.json +3 -3
- package/node_modules/@ocean/brain/package.json +1 -1
- package/node_modules/@ocean/context/package.json +1 -1
- package/node_modules/@ocean/core/dist/shared/paths.js +12 -1
- package/node_modules/@ocean/core/package.json +1 -1
- package/node_modules/@ocean/loop/package.json +1 -1
- package/node_modules/@ocean/market/package.json +1 -1
- package/node_modules/@ocean/services/dist/brief/brief.js +2 -2
- package/node_modules/@ocean/services/dist/day/day.js +6 -5
- package/node_modules/@ocean/services/dist/distill/distill.js +8 -8
- package/node_modules/@ocean/services/dist/harvest/harvest.js +56 -31
- package/node_modules/@ocean/services/dist/hygiene/hygiene.js +2 -2
- package/node_modules/@ocean/services/dist/scorecard/scorecard.js +2 -2
- package/node_modules/@ocean/services/dist/upkeep/upkeep.js +2 -2
- package/node_modules/@ocean/services/package.json +1 -1
- package/ocean-marketplace.json +38 -38
- package/package.json +7 -7
- package/skills/core/daily-harvest/SKILL.md +3 -3
- package/skills/core/weekly-review/SKILL.md +1 -1
|
@@ -21,6 +21,12 @@ const EVENTS = {
|
|
|
21
21
|
flags: "",
|
|
22
22
|
pattern: /\bhook pre-compact\b/,
|
|
23
23
|
},
|
|
24
|
+
// Every prompt goes through the skill router, which names the skill it calls for (T-325).
|
|
25
|
+
UserPromptSubmit: {
|
|
26
|
+
action: "prompt",
|
|
27
|
+
flags: "",
|
|
28
|
+
pattern: /\bhook prompt\b/,
|
|
29
|
+
},
|
|
24
30
|
};
|
|
25
31
|
export const HOOK_ADAPTERS = [
|
|
26
32
|
{
|
|
@@ -28,7 +34,7 @@ export const HOOK_ADAPTERS = [
|
|
|
28
34
|
hookClient: "claude",
|
|
29
35
|
file: ".claude/settings.json",
|
|
30
36
|
windowsShell: "powershell",
|
|
31
|
-
events: ["SessionStart", "SessionEnd", "PreCompact"],
|
|
37
|
+
events: ["SessionStart", "SessionEnd", "PreCompact", "UserPromptSubmit"],
|
|
32
38
|
group: (command, windows) => ({
|
|
33
39
|
hooks: [
|
|
34
40
|
{
|
|
@@ -45,8 +51,9 @@ export const HOOK_ADAPTERS = [
|
|
|
45
51
|
hookClient: "codex",
|
|
46
52
|
file: ".codex/hooks.json",
|
|
47
53
|
windowsShell: "cmd",
|
|
48
|
-
|
|
49
|
-
|
|
54
|
+
// Codex 0.156 reads additionalContext from UserPromptSubmit too.
|
|
55
|
+
events: ["SessionStart", "SessionEnd", "UserPromptSubmit"],
|
|
56
|
+
group: (command, _windows, event) => event !== "SessionStart"
|
|
50
57
|
? { hooks: [{ type: "command", command, timeout: 10 }] }
|
|
51
58
|
: {
|
|
52
59
|
matcher: "startup|resume",
|
|
@@ -65,8 +72,10 @@ export const HOOK_ADAPTERS = [
|
|
|
65
72
|
hookClient: "gemini",
|
|
66
73
|
file: ".gemini/settings.json",
|
|
67
74
|
windowsShell: "powershell",
|
|
68
|
-
// Gemini CLI 0.58 also fires SessionEnd (fireSessionEndEvent), T-307.
|
|
69
|
-
|
|
75
|
+
// Gemini CLI 0.58 also fires SessionEnd (fireSessionEndEvent), T-307. Its per-prompt event
|
|
76
|
+
// is BeforeAgent, whose additionalContext 0.61 adds to the turn (T-325).
|
|
77
|
+
events: ["SessionStart", "SessionEnd", "UserPromptSubmit"],
|
|
78
|
+
key: (event) => (event === "UserPromptSubmit" ? "BeforeAgent" : event),
|
|
70
79
|
// Gemini's hook timeout is in milliseconds.
|
|
71
80
|
group: (command) => ({
|
|
72
81
|
matcher: "*",
|
|
@@ -80,7 +89,7 @@ export const HOOK_ADAPTERS = [
|
|
|
80
89
|
hookClient: "qwen",
|
|
81
90
|
file: ".qwen/settings.json",
|
|
82
91
|
windowsShell: "powershell",
|
|
83
|
-
events: ["SessionStart", "SessionEnd"],
|
|
92
|
+
events: ["SessionStart", "SessionEnd", "UserPromptSubmit"],
|
|
84
93
|
group: (command, windows, event) => ({
|
|
85
94
|
...(event === "SessionStart" ? { matcher: "startup|resume" } : {}),
|
|
86
95
|
hooks: [
|
|
@@ -296,7 +305,7 @@ export async function restoreHooks(options) {
|
|
|
296
305
|
const conflicts = [];
|
|
297
306
|
const undo = newBatch();
|
|
298
307
|
for (const entry of entries) {
|
|
299
|
-
const label = `${entry.client}:${entry.key === "SessionEnd" ? "end-hook" : entry.key === "PreCompact" ? "compact-hook" : "hook"}`;
|
|
308
|
+
const label = `${entry.client}:${entry.key === "SessionEnd" ? "end-hook" : entry.key === "PreCompact" ? "compact-hook" : entry.key === "UserPromptSubmit" ? "prompt-hook" : "hook"}`;
|
|
300
309
|
// Set per attempt: edit() may run the change again when the file moved under it.
|
|
301
310
|
const outcome = { restored: false };
|
|
302
311
|
await edit(path.join(env.home, entry.file), (text) => {
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { syncCoreSkills } from "@ocean/market/skills/core-skill-sync.js";
|
|
2
2
|
import { copyClientSkills, retireCoreFromHub, } from "@ocean/market/skills/skill-hub.js";
|
|
3
|
+
import { buildSkillIndex } from "./skill-router.js";
|
|
3
4
|
// Keeps every client's skills current with no command run: the session-start sync and
|
|
4
5
|
// `ocean market install|update` call it. Hub skills (installed from the market or made there)
|
|
5
6
|
// first, then the engine's core skills, so the engine's version of a core skill wins. A copy the
|
|
@@ -39,6 +40,13 @@ export async function autoSyncSkills(home) {
|
|
|
39
40
|
catch (error) {
|
|
40
41
|
summary.failed.push(`core: ${error instanceof Error ? error.message : String(error)}`);
|
|
41
42
|
}
|
|
43
|
+
// The skill router's index (T-325) picks up descriptions edited since the last session.
|
|
44
|
+
try {
|
|
45
|
+
await buildSkillIndex(home);
|
|
46
|
+
}
|
|
47
|
+
catch (error) {
|
|
48
|
+
summary.failed.push(`index: ${error instanceof Error ? error.message : String(error)}`);
|
|
49
|
+
}
|
|
42
50
|
return summary;
|
|
43
51
|
}
|
|
44
52
|
//# sourceMappingURL=skill-auto-sync.js.map
|
|
@@ -8,9 +8,11 @@ import { oceanPath, SYSTEM_DIR } from "@ocean/core/shared/paths.js";
|
|
|
8
8
|
// `user-invocable-only`). Codex, Gemini and Hermes have no such setting and load every installed
|
|
9
9
|
// skill's description on every request, so `ocean client sync` disables the same skills there:
|
|
10
10
|
// a generated block of `[[skills.config]] enabled = false` entries in ~/.codex/config.toml, and
|
|
11
|
-
// names in `skills.disabled` of ~/.gemini/settings.json and ~/.hermes/config.yaml.
|
|
12
|
-
//
|
|
13
|
-
//
|
|
11
|
+
// names in `skills.disabled` of ~/.gemini/settings.json and ~/.hermes/config.yaml. Their native
|
|
12
|
+
// skill loaders then skip it, but its files stay on disk: the skill router (skill-router.ts,
|
|
13
|
+
// T-325) still indexes `user-invocable-only` skills and, in a client with a per-prompt hook
|
|
14
|
+
// (Codex, Gemini), points the model at the SKILL.md path to read. Hermes has no verified prompt
|
|
15
|
+
// hook, so a hidden skill stays unreachable there. Only `off` removes a skill from the router too.
|
|
14
16
|
const BEGIN = "# ocean:skill-filter:begin — generated by `ocean client sync` from Claude's skillOverrides; edit those, not this";
|
|
15
17
|
const END = "# ocean:skill-filter:end";
|
|
16
18
|
// SKILL.md files directly under `root/<dir>/`, plus one category level deeper when `nested`.
|
|
@@ -0,0 +1,438 @@
|
|
|
1
|
+
import { mkdir, readdir, readFile, stat } from "node:fs/promises";
|
|
2
|
+
import os from "node:os";
|
|
3
|
+
import path from "node:path";
|
|
4
|
+
import { atomicWrite } from "@ocean/core/shared/fs-utils.js";
|
|
5
|
+
import { oceanPath, SYSTEM_DIR } from "@ocean/core/shared/paths.js";
|
|
6
|
+
import { clientSkillRoots } from "@ocean/market/skills/core-skill-sync.js";
|
|
7
|
+
// Below this a match is noise; tuned on the owner's installed skills (`ocean skill route`).
|
|
8
|
+
export const ROUTE_THRESHOLD = 7;
|
|
9
|
+
// A runner-up within this share of the top score counts as close (named, or ambiguous).
|
|
10
|
+
const SECOND_RATIO = 0.8;
|
|
11
|
+
// What a word found in only one skill is worth (≈ its raw IDF across ~150 skills).
|
|
12
|
+
const IDF_CEILING = 4.6;
|
|
13
|
+
// Long pastes (logs, exports) are routed on their opening only.
|
|
14
|
+
const MESSAGE_CHARS = 1_500;
|
|
15
|
+
function skillRoots(home) {
|
|
16
|
+
return [
|
|
17
|
+
{ client: "claude", dir: clientSkillRoots.claude(home), nested: false },
|
|
18
|
+
{ client: "codex", dir: clientSkillRoots.codex(home), nested: true },
|
|
19
|
+
{ client: "gemini", dir: clientSkillRoots.gemini(home), nested: false },
|
|
20
|
+
{ client: "hermes", dir: clientSkillRoots.hermes(home), nested: true },
|
|
21
|
+
{
|
|
22
|
+
client: "agents",
|
|
23
|
+
dir: path.join(home, ".agents", "skills"),
|
|
24
|
+
nested: false,
|
|
25
|
+
},
|
|
26
|
+
];
|
|
27
|
+
}
|
|
28
|
+
const indexPath = () => oceanPath(SYSTEM_DIR, "state", "skill-index.json");
|
|
29
|
+
const statePath = () => oceanPath(SYSTEM_DIR, "state", "skill-router.json");
|
|
30
|
+
// One frontmatter field, with folded (`>`), literal (`|`) and indented continuation lines.
|
|
31
|
+
export function frontmatterField(text, key) {
|
|
32
|
+
const normalized = text.replace(/\r\n/g, "\n");
|
|
33
|
+
if (!normalized.startsWith("---"))
|
|
34
|
+
return "";
|
|
35
|
+
const end = normalized.indexOf("\n---", 3);
|
|
36
|
+
const lines = normalized.slice(3, end < 0 ? undefined : end).split("\n");
|
|
37
|
+
const pattern = new RegExp(`^${key}:\\s*(.*)$`);
|
|
38
|
+
for (let i = 0; i < lines.length; i++) {
|
|
39
|
+
const match = pattern.exec(lines[i]);
|
|
40
|
+
if (!match)
|
|
41
|
+
continue;
|
|
42
|
+
const first = match[1].trim();
|
|
43
|
+
const parts = /^[>|][+-]?$/.test(first) ? [] : [first];
|
|
44
|
+
for (let j = i + 1; j < lines.length && /^\s+\S/.test(lines[j]); j++)
|
|
45
|
+
parts.push(lines[j].trim());
|
|
46
|
+
return parts
|
|
47
|
+
.join(" ")
|
|
48
|
+
.replace(/^["']|["']$/g, "")
|
|
49
|
+
.trim();
|
|
50
|
+
}
|
|
51
|
+
return "";
|
|
52
|
+
}
|
|
53
|
+
// "Use when the user says start my day, good morning, or plan today." → the quoted-in-prose
|
|
54
|
+
// phrases; also anything in double quotes. Placeholders (`X`) are dropped.
|
|
55
|
+
export function triggerPhrases(description) {
|
|
56
|
+
const phrases = new Set();
|
|
57
|
+
const add = (raw) => {
|
|
58
|
+
const phrase = normalizeText(raw)
|
|
59
|
+
.replace(/^(?:or|and)\s+/, "")
|
|
60
|
+
.replace(/\s+\b[xy]\b$/, "")
|
|
61
|
+
.trim();
|
|
62
|
+
const words = phrase.split(" ").filter(Boolean);
|
|
63
|
+
if (phrase.length >= 4 && words.length <= 6 && words.some(isContentWord))
|
|
64
|
+
phrases.add(phrase);
|
|
65
|
+
};
|
|
66
|
+
const lead = /\b(?:says?|mentions?|types?|asks? (?:for|to|about))\b:?\s+([^.]+?)(?:\.(?:\s|$)|$)/gi;
|
|
67
|
+
for (const match of description.matchAll(lead))
|
|
68
|
+
for (const part of match[1].split(/,|;/))
|
|
69
|
+
add(part);
|
|
70
|
+
for (const match of description.matchAll(/["“]([^"”]{3,60})["”]/g))
|
|
71
|
+
add(match[1]);
|
|
72
|
+
return [...phrases];
|
|
73
|
+
}
|
|
74
|
+
async function scanRoot(root, nested, found, off) {
|
|
75
|
+
let entries;
|
|
76
|
+
try {
|
|
77
|
+
entries = (await readdir(root.dir)).sort();
|
|
78
|
+
}
|
|
79
|
+
catch {
|
|
80
|
+
return;
|
|
81
|
+
}
|
|
82
|
+
for (const entry of entries) {
|
|
83
|
+
if (entry.startsWith(".") && !nested)
|
|
84
|
+
continue;
|
|
85
|
+
const file = path.join(root.dir, entry, "SKILL.md");
|
|
86
|
+
let text;
|
|
87
|
+
try {
|
|
88
|
+
text = await readFile(file, "utf8");
|
|
89
|
+
}
|
|
90
|
+
catch {
|
|
91
|
+
if (nested)
|
|
92
|
+
await scanRoot({ ...root, dir: path.join(root.dir, entry) }, false, found, off);
|
|
93
|
+
continue;
|
|
94
|
+
}
|
|
95
|
+
const name = frontmatterField(text, "name") || entry;
|
|
96
|
+
if (off.has(name))
|
|
97
|
+
continue;
|
|
98
|
+
if (/^true$/i.test(frontmatterField(text, "disable-model-invocation")))
|
|
99
|
+
continue;
|
|
100
|
+
const known = found.get(name);
|
|
101
|
+
if (known) {
|
|
102
|
+
known.files[root.client] ??= file;
|
|
103
|
+
continue;
|
|
104
|
+
}
|
|
105
|
+
const description = frontmatterField(text, "description");
|
|
106
|
+
if (!description)
|
|
107
|
+
continue;
|
|
108
|
+
found.set(name, {
|
|
109
|
+
name,
|
|
110
|
+
description,
|
|
111
|
+
triggers: triggerPhrases(description),
|
|
112
|
+
files: { [root.client]: file },
|
|
113
|
+
});
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
// Skills the owner switched fully off in Claude (`skillOverrides: off`) stay out of the index;
|
|
117
|
+
// hidden ones (`user-invocable-only`) are what the router is for.
|
|
118
|
+
async function claudeOffSkills(home) {
|
|
119
|
+
try {
|
|
120
|
+
const parsed = JSON.parse(await readFile(path.join(home, ".claude", "settings.json"), "utf8"));
|
|
121
|
+
const overrides = parsed?.skillOverrides;
|
|
122
|
+
if (!overrides || typeof overrides !== "object")
|
|
123
|
+
return new Set();
|
|
124
|
+
return new Set(Object.entries(overrides)
|
|
125
|
+
.filter(([, value]) => value === "off")
|
|
126
|
+
.map(([name]) => name));
|
|
127
|
+
}
|
|
128
|
+
catch {
|
|
129
|
+
return new Set();
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
// Rebuilt by the session-start skill sync and whenever a skills root changed since.
|
|
133
|
+
export async function buildSkillIndex(home = os.homedir(), write = true) {
|
|
134
|
+
const off = await claudeOffSkills(home);
|
|
135
|
+
const found = new Map();
|
|
136
|
+
for (const root of skillRoots(home))
|
|
137
|
+
await scanRoot(root, root.nested, found, off);
|
|
138
|
+
const index = {
|
|
139
|
+
version: 1,
|
|
140
|
+
builtAt: Date.now(),
|
|
141
|
+
skills: [...found.values()].sort((a, b) => a.name.localeCompare(b.name)),
|
|
142
|
+
};
|
|
143
|
+
if (write) {
|
|
144
|
+
await mkdir(path.dirname(indexPath()), { recursive: true });
|
|
145
|
+
await atomicWrite(indexPath(), `${JSON.stringify(index)}\n`);
|
|
146
|
+
}
|
|
147
|
+
return index;
|
|
148
|
+
}
|
|
149
|
+
// The cached index, rebuilt when missing or older than a skills root (a skill added or removed).
|
|
150
|
+
export async function loadSkillIndex(home = os.homedir()) {
|
|
151
|
+
let cached = null;
|
|
152
|
+
try {
|
|
153
|
+
const parsed = JSON.parse(await readFile(indexPath(), "utf8"));
|
|
154
|
+
if (parsed?.version === 1 && Array.isArray(parsed.skills))
|
|
155
|
+
cached = parsed;
|
|
156
|
+
}
|
|
157
|
+
catch { }
|
|
158
|
+
if (cached) {
|
|
159
|
+
let newest = 0;
|
|
160
|
+
for (const root of skillRoots(home)) {
|
|
161
|
+
const info = await stat(root.dir).catch(() => null);
|
|
162
|
+
if (info)
|
|
163
|
+
newest = Math.max(newest, info.mtimeMs);
|
|
164
|
+
}
|
|
165
|
+
if (newest <= cached.builtAt)
|
|
166
|
+
return cached;
|
|
167
|
+
}
|
|
168
|
+
return buildSkillIndex(home);
|
|
169
|
+
}
|
|
170
|
+
const STOP_WORDS = new Set(("a an the and or but if of to in on at by for with from as is are was were be been being " +
|
|
171
|
+
"it its this that these those i me my we our us you your he she they them their what which " +
|
|
172
|
+
"who whom how when where why can could should would will shall do does did done doing have " +
|
|
173
|
+
"has had not no yes so than then there here about into over under up down out any all some " +
|
|
174
|
+
"each every more most other such only own same too very just also use used using user users " +
|
|
175
|
+
"owner says say said ask asks asked want wants need needs please let lets get got make made " +
|
|
176
|
+
"via per etc skill skills like one two new now way well really thing things help").split(" "));
|
|
177
|
+
const isContentWord = (word) => word.length >= 2 && !STOP_WORDS.has(word);
|
|
178
|
+
function normalizeText(text) {
|
|
179
|
+
return (text
|
|
180
|
+
.toLowerCase()
|
|
181
|
+
.normalize("NFKC")
|
|
182
|
+
.match(/[\p{L}\p{N}]+/gu)
|
|
183
|
+
?.join(" ") ?? "");
|
|
184
|
+
}
|
|
185
|
+
// Light suffix stripping so "writing tests" meets "write a test"; the same on both sides.
|
|
186
|
+
function stem(word) {
|
|
187
|
+
let out = word;
|
|
188
|
+
if (out.length > 5 && out.endsWith("ing"))
|
|
189
|
+
out = out.slice(0, -3);
|
|
190
|
+
else if (out.length > 4 && out.endsWith("ed"))
|
|
191
|
+
out = out.slice(0, -2);
|
|
192
|
+
else if (out.length > 4 && out.endsWith("es"))
|
|
193
|
+
out = out.slice(0, -2);
|
|
194
|
+
else if (out.length > 3 && out.endsWith("s") && !out.endsWith("ss"))
|
|
195
|
+
out = out.slice(0, -1);
|
|
196
|
+
if (out.length > 3 && out.endsWith("e"))
|
|
197
|
+
out = out.slice(0, -1);
|
|
198
|
+
return out;
|
|
199
|
+
}
|
|
200
|
+
export function tokenize(text) {
|
|
201
|
+
return normalizeText(text).split(" ").filter(isContentWord).map(stem);
|
|
202
|
+
}
|
|
203
|
+
// Message shapes that carry intent no single word does: "Zustand or Redux?" is a comparison.
|
|
204
|
+
function expansions(message) {
|
|
205
|
+
const words = [];
|
|
206
|
+
const text = message.trim();
|
|
207
|
+
if (/\b(?:vs\.?|versus|better than|difference between|which is better|pros and cons)\b/i.test(text) ||
|
|
208
|
+
/^[^\n?]{1,60}\s+or\s+[^\n?]{1,60}\?\s*$/i.test(text))
|
|
209
|
+
words.push("compare");
|
|
210
|
+
return words;
|
|
211
|
+
}
|
|
212
|
+
// Words the working directory names: its package.json dependencies and its top-level file
|
|
213
|
+
// names (`vitest.config.ts` → vitest, `graphify-out` → graphify).
|
|
214
|
+
export async function projectSignals(cwd) {
|
|
215
|
+
const terms = new Set();
|
|
216
|
+
const dirs = [cwd];
|
|
217
|
+
let current = cwd;
|
|
218
|
+
for (let depth = 0; depth < 5; depth++) {
|
|
219
|
+
const marker = await stat(path.join(current, "package.json")).catch(() => stat(path.join(current, ".git")).catch(() => null));
|
|
220
|
+
if (marker) {
|
|
221
|
+
if (current !== cwd)
|
|
222
|
+
dirs.push(current);
|
|
223
|
+
break;
|
|
224
|
+
}
|
|
225
|
+
const parent = path.dirname(current);
|
|
226
|
+
if (parent === current)
|
|
227
|
+
break;
|
|
228
|
+
current = parent;
|
|
229
|
+
}
|
|
230
|
+
for (const dir of dirs) {
|
|
231
|
+
try {
|
|
232
|
+
for (const entry of await readdir(dir))
|
|
233
|
+
terms.add(entry.toLowerCase().split(/[.\-_]/)[0]);
|
|
234
|
+
}
|
|
235
|
+
catch { }
|
|
236
|
+
try {
|
|
237
|
+
const pkg = JSON.parse(await readFile(path.join(dir, "package.json"), "utf8"));
|
|
238
|
+
for (const deps of [pkg?.dependencies, pkg?.devDependencies])
|
|
239
|
+
if (deps && typeof deps === "object")
|
|
240
|
+
for (const dep of Object.keys(deps)) {
|
|
241
|
+
const [scope, name] = dep.startsWith("@")
|
|
242
|
+
? dep.slice(1).split("/")
|
|
243
|
+
: [dep, ""];
|
|
244
|
+
terms.add(`dep:${scope.toLowerCase()}`);
|
|
245
|
+
if (name)
|
|
246
|
+
terms.add(`dep:${name.toLowerCase()}`);
|
|
247
|
+
}
|
|
248
|
+
}
|
|
249
|
+
catch { }
|
|
250
|
+
}
|
|
251
|
+
terms.delete("");
|
|
252
|
+
return terms;
|
|
253
|
+
}
|
|
254
|
+
// Whether the working directory points at this skill: a file named like it, or a dependency
|
|
255
|
+
// named like it (or like its first word: `next` → next-best-practices).
|
|
256
|
+
function projectHit(name, signals) {
|
|
257
|
+
const lower = name.toLowerCase();
|
|
258
|
+
const head = lower.split("-")[0];
|
|
259
|
+
return (signals.has(lower) ||
|
|
260
|
+
signals.has(`dep:${lower}`) ||
|
|
261
|
+
(head.length >= 4 && signals.has(`dep:${head}`)));
|
|
262
|
+
}
|
|
263
|
+
const PREFERRED_ROOT = {
|
|
264
|
+
claude: ["claude"],
|
|
265
|
+
codex: ["codex", "agents"],
|
|
266
|
+
gemini: ["gemini", "agents"],
|
|
267
|
+
hermes: ["hermes"],
|
|
268
|
+
qwen: ["agents"],
|
|
269
|
+
};
|
|
270
|
+
function fileFor(skill, client) {
|
|
271
|
+
for (const root of PREFERRED_ROOT[client] ?? [])
|
|
272
|
+
if (skill.files[root])
|
|
273
|
+
return skill.files[root];
|
|
274
|
+
return Object.values(skill.files)[0] ?? "";
|
|
275
|
+
}
|
|
276
|
+
// BM25 over each description (the name counts double), plus trigger-phrase hits and the
|
|
277
|
+
// working-directory signal. Pure: the same index, message and signals give the same answer.
|
|
278
|
+
export function routeSkills(index, message, options = {}) {
|
|
279
|
+
const empty = { matches: [], candidates: [] };
|
|
280
|
+
const text = message.slice(0, MESSAGE_CHARS);
|
|
281
|
+
if (!text.trim() || text.trimStart().startsWith("/"))
|
|
282
|
+
return empty;
|
|
283
|
+
const extra = expansions(text);
|
|
284
|
+
const query = [...new Set([...tokenize(text), ...extra.map(stem)])];
|
|
285
|
+
if (!query.length)
|
|
286
|
+
return empty;
|
|
287
|
+
const spoken = ` ${[normalizeText(text), ...extra].join(" ")} `;
|
|
288
|
+
const prepared = index.skills.map((skill) => {
|
|
289
|
+
const name = new Set(tokenize(skill.name.replace(/[-_]/g, " ")));
|
|
290
|
+
const tf = new Map();
|
|
291
|
+
const words = tokenize(skill.description);
|
|
292
|
+
for (const word of words)
|
|
293
|
+
tf.set(word, (tf.get(word) ?? 0) + 1);
|
|
294
|
+
for (const word of name)
|
|
295
|
+
tf.set(word, (tf.get(word) ?? 0) + 2);
|
|
296
|
+
return { skill, name, tf, length: words.length + name.size * 2 };
|
|
297
|
+
});
|
|
298
|
+
const count = prepared.length || 1;
|
|
299
|
+
const average = prepared.reduce((sum, item) => sum + item.length, 0) / count || 1;
|
|
300
|
+
const df = new Map();
|
|
301
|
+
for (const item of prepared)
|
|
302
|
+
for (const word of item.tf.keys())
|
|
303
|
+
df.set(word, (df.get(word) ?? 0) + 1);
|
|
304
|
+
// IDF is scaled so a word unique to one skill weighs IDF_CEILING however many skills are
|
|
305
|
+
// installed: the threshold then means the same with 15 skills or 150.
|
|
306
|
+
const rarest = Math.log(1 + (count - 0.5) / 1.5) || 1;
|
|
307
|
+
const k1 = 1.2;
|
|
308
|
+
const b = 0.75;
|
|
309
|
+
const signals = options.signals ?? new Set();
|
|
310
|
+
const scored = [];
|
|
311
|
+
for (const item of prepared) {
|
|
312
|
+
let score = 0;
|
|
313
|
+
const why = [];
|
|
314
|
+
let words = 0;
|
|
315
|
+
for (const word of query) {
|
|
316
|
+
const tf = item.tf.get(word);
|
|
317
|
+
if (!tf)
|
|
318
|
+
continue;
|
|
319
|
+
const seen = df.get(word) ?? 0;
|
|
320
|
+
const idf = (Math.log(1 + (count - seen + 0.5) / (seen + 0.5)) / rarest) *
|
|
321
|
+
IDF_CEILING;
|
|
322
|
+
const norm = k1 * (1 - b + (b * item.length) / average);
|
|
323
|
+
score += (idf * (tf * (k1 + 1))) / (tf + norm);
|
|
324
|
+
words++;
|
|
325
|
+
why.push(word);
|
|
326
|
+
}
|
|
327
|
+
let phrases = 0;
|
|
328
|
+
for (const phrase of item.skill.triggers)
|
|
329
|
+
if (spoken.includes(` ${phrase} `) && phrases < 2) {
|
|
330
|
+
score += 4 + phrase.split(" ").length;
|
|
331
|
+
phrases++;
|
|
332
|
+
why.push(`"${phrase}"`);
|
|
333
|
+
}
|
|
334
|
+
// One shared word is a coincidence unless it is the skill's own name or a phrase it lists.
|
|
335
|
+
const nameHit = query.some((word) => item.name.has(word));
|
|
336
|
+
if (words < 2 && !phrases && !nameHit)
|
|
337
|
+
continue;
|
|
338
|
+
if (score > 0 && projectHit(item.skill.name, signals)) {
|
|
339
|
+
score += 4;
|
|
340
|
+
why.push("project");
|
|
341
|
+
}
|
|
342
|
+
if (score <= 0)
|
|
343
|
+
continue;
|
|
344
|
+
scored.push({
|
|
345
|
+
name: item.skill.name,
|
|
346
|
+
file: fileFor(item.skill, options.client ?? "claude"),
|
|
347
|
+
score: Math.round(score * 10) / 10,
|
|
348
|
+
why,
|
|
349
|
+
});
|
|
350
|
+
}
|
|
351
|
+
scored.sort((a, b) => b.score - a.score || a.name.localeCompare(b.name));
|
|
352
|
+
const candidates = scored.slice(0, options.limit ?? 5);
|
|
353
|
+
const top = scored[0];
|
|
354
|
+
if (!top || top.score < ROUTE_THRESHOLD)
|
|
355
|
+
return { matches: [], candidates };
|
|
356
|
+
// Close runners-up: one is named alongside the top skill; two or more mean the message is
|
|
357
|
+
// generic ("write tests" with three test skills and nothing in the project to choose), so
|
|
358
|
+
// nothing is named.
|
|
359
|
+
const close = scored
|
|
360
|
+
.slice(1)
|
|
361
|
+
.filter((item) => item.score >= top.score * SECOND_RATIO);
|
|
362
|
+
if (close.length >= 2)
|
|
363
|
+
return { matches: [], candidates };
|
|
364
|
+
const matches = [top, ...close];
|
|
365
|
+
return { matches, candidates };
|
|
366
|
+
}
|
|
367
|
+
export function routerLine(matches) {
|
|
368
|
+
if (matches.length === 1)
|
|
369
|
+
return `Skill router: this request matches the "${matches[0].name}" skill. Read ${matches[0].file} and follow it if it fits.`;
|
|
370
|
+
const list = matches.map((match) => `"${match.name}" (${match.file})`);
|
|
371
|
+
return `Skill router: this request matches the skills ${list.join(" and ")}. Read the one that fits and follow it.`;
|
|
372
|
+
}
|
|
373
|
+
async function readState() {
|
|
374
|
+
try {
|
|
375
|
+
const parsed = JSON.parse(await readFile(statePath(), "utf8"));
|
|
376
|
+
return {
|
|
377
|
+
sessions: parsed?.sessions && typeof parsed.sessions === "object"
|
|
378
|
+
? parsed.sessions
|
|
379
|
+
: {},
|
|
380
|
+
hits: parsed?.hits && typeof parsed.hits === "object" ? parsed.hits : {},
|
|
381
|
+
};
|
|
382
|
+
}
|
|
383
|
+
catch {
|
|
384
|
+
return { sessions: {}, hits: {} };
|
|
385
|
+
}
|
|
386
|
+
}
|
|
387
|
+
const SESSION_TTL_MS = 3 * 24 * 60 * 60 * 1000;
|
|
388
|
+
const HOOK_EVENT = {
|
|
389
|
+
claude: "UserPromptSubmit",
|
|
390
|
+
codex: "UserPromptSubmit",
|
|
391
|
+
qwen: "UserPromptSubmit",
|
|
392
|
+
gemini: "BeforeAgent",
|
|
393
|
+
};
|
|
394
|
+
export const PROMPT_HOOK_CLIENTS = Object.keys(HOOK_EVENT);
|
|
395
|
+
// `ocean hook prompt --client <c>`: the hook payload in, the client's additional-context
|
|
396
|
+
// output (or nothing) out. Never throws on a bad payload: a prompt hook must not block a prompt.
|
|
397
|
+
export async function skillRouterHook(payload, client, home = os.homedir()) {
|
|
398
|
+
const prompt = typeof payload.prompt === "string" ? payload.prompt : "";
|
|
399
|
+
if (!prompt.trim())
|
|
400
|
+
return null;
|
|
401
|
+
const cwd = typeof payload.cwd === "string" ? payload.cwd : process.cwd();
|
|
402
|
+
const session = typeof payload.session_id === "string" ? payload.session_id : "";
|
|
403
|
+
const index = await loadSkillIndex(home);
|
|
404
|
+
const { matches } = routeSkills(index, prompt, {
|
|
405
|
+
signals: await projectSignals(cwd),
|
|
406
|
+
client,
|
|
407
|
+
});
|
|
408
|
+
if (!matches.length)
|
|
409
|
+
return null;
|
|
410
|
+
const state = await readState();
|
|
411
|
+
const seen = new Set(session ? (state.sessions[session]?.skills ?? []) : []);
|
|
412
|
+
const fresh = matches.filter((match) => !seen.has(match.name));
|
|
413
|
+
if (!fresh.length)
|
|
414
|
+
return null;
|
|
415
|
+
const now = Date.now();
|
|
416
|
+
for (const [id, entry] of Object.entries(state.sessions))
|
|
417
|
+
if (!entry || now - entry.at > SESSION_TTL_MS)
|
|
418
|
+
delete state.sessions[id];
|
|
419
|
+
if (session)
|
|
420
|
+
state.sessions[session] = {
|
|
421
|
+
at: now,
|
|
422
|
+
skills: [...seen, ...fresh.map((match) => match.name)],
|
|
423
|
+
};
|
|
424
|
+
for (const match of fresh)
|
|
425
|
+
state.hits[match.name] = (state.hits[match.name] ?? 0) + 1;
|
|
426
|
+
try {
|
|
427
|
+
await mkdir(path.dirname(statePath()), { recursive: true });
|
|
428
|
+
await atomicWrite(statePath(), `${JSON.stringify(state, null, 2)}\n`);
|
|
429
|
+
}
|
|
430
|
+
catch { }
|
|
431
|
+
return {
|
|
432
|
+
hookSpecificOutput: {
|
|
433
|
+
hookEventName: HOOK_EVENT[client] ?? "UserPromptSubmit",
|
|
434
|
+
additionalContext: routerLine(fresh),
|
|
435
|
+
},
|
|
436
|
+
};
|
|
437
|
+
}
|
|
438
|
+
//# sourceMappingURL=skill-router.js.map
|
|
@@ -9,7 +9,7 @@ import { scorecardFile, searchEvalFile, } from "@ocean/services/scorecard/scorec
|
|
|
9
9
|
import { previousScorecard, renderDigest, runUpkeepJobs, scorecardMoves, writeDigest, } from "@ocean/services/upkeep/upkeep.js";
|
|
10
10
|
import { listSchedules } from "../scheduler/local-scheduler.js";
|
|
11
11
|
// Nightly upkeep (T-322): each job is a child `ocean` process with a timeout; the results become
|
|
12
|
-
// the morning digest in 01-daily/digest/. Once a day through `ocean rhythm` (ifDue), and the
|
|
12
|
+
// the morning digest in 01-daily/reports/digest/. Once a day through `ocean rhythm` (ifDue), and the
|
|
13
13
|
// monthly memory hygiene joins the first run of a month that has no report yet.
|
|
14
14
|
const MINUTE = 60_000;
|
|
15
15
|
const OUTPUT_LIMIT = 4 * 1024 * 1024;
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { localDate } from "@ocean/core/shared/local-date.js";
|
|
2
2
|
import { buildBrief } from "@ocean/services/brief/brief.js";
|
|
3
3
|
// `ocean brief [--weekly] [--dry-run] [--date YYYY-MM-DD]` (T-314): what moved in what the owner
|
|
4
|
-
// follows, written to 01-daily/briefs/.
|
|
4
|
+
// follows, written to 01-daily/reports/briefs/.
|
|
5
5
|
export async function runBriefCommand(args) {
|
|
6
6
|
const at = args.indexOf("--date");
|
|
7
7
|
const date = at >= 0 ? args[at + 1] : localDate();
|
|
@@ -41,6 +41,7 @@ import { configureClaudeCodeWrapper } from "../../application/integrations/claud
|
|
|
41
41
|
import { repairEngineEntries } from "../../application/integrations/engine-entry-repair.js";
|
|
42
42
|
import { autoSyncSkills } from "../../application/integrations/skill-auto-sync.js";
|
|
43
43
|
import { syncSkillFilter } from "../../application/integrations/skill-filter.js";
|
|
44
|
+
import { buildSkillIndex, loadSkillIndex, PROMPT_HOOK_CLIENTS, projectSignals, ROUTE_THRESHOLD, routerLine, routeSkills, skillRouterHook, } from "../../application/integrations/skill-router.js";
|
|
44
45
|
import { selectProfileForTask } from "../../application/profiles/profile-suggestion.js";
|
|
45
46
|
import { listSchedules, runDueSchedules, runSchedule, runSchedulerWorker, runSchedulerWorkerOnce, saveSchedule, setScheduleEnabled, } from "../../application/scheduler/local-scheduler.js";
|
|
46
47
|
import { defaultAgentRuntime, defaultBrainIndexPort, defaultProviderRegistry, defaultSessionStoreFactory, defaultSessionStoreOpener, defaultWrapperManager, } from "../../composition/runtime.js";
|
|
@@ -689,6 +690,36 @@ async function commandHook() {
|
|
|
689
690
|
}
|
|
690
691
|
return;
|
|
691
692
|
}
|
|
693
|
+
if (action === "prompt") {
|
|
694
|
+
// Per-prompt skill router (T-325): names the skill the message calls for, or prints nothing.
|
|
695
|
+
// A failure is silent and exits 0, so a broken index never blocks the owner's prompt.
|
|
696
|
+
const flags = process.argv.slice(4);
|
|
697
|
+
const inline = flags.find((arg) => arg.startsWith("--client="));
|
|
698
|
+
const clientIndex = flags.indexOf("--client");
|
|
699
|
+
const client = inline
|
|
700
|
+
? inline.slice("--client=".length)
|
|
701
|
+
: clientIndex >= 0
|
|
702
|
+
? (flags[clientIndex + 1] ?? "")
|
|
703
|
+
: "claude";
|
|
704
|
+
if (!PROMPT_HOOK_CLIENTS.includes(client)) {
|
|
705
|
+
console.error(promptUsage);
|
|
706
|
+
process.exitCode = 1;
|
|
707
|
+
return;
|
|
708
|
+
}
|
|
709
|
+
try {
|
|
710
|
+
const raw = await readBoundedStdin();
|
|
711
|
+
const parsed = raw.trim() ? JSON.parse(raw) : {};
|
|
712
|
+
if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
|
|
713
|
+
const output = await skillRouterHook(parsed, client);
|
|
714
|
+
if (output)
|
|
715
|
+
console.log(JSON.stringify(output));
|
|
716
|
+
}
|
|
717
|
+
}
|
|
718
|
+
catch (error) {
|
|
719
|
+
console.error(error instanceof Error ? error.message : String(error));
|
|
720
|
+
}
|
|
721
|
+
return;
|
|
722
|
+
}
|
|
692
723
|
if (action === "session-start") {
|
|
693
724
|
const flags = process.argv.slice(4);
|
|
694
725
|
if (flags.includes("--repair"))
|
|
@@ -753,6 +784,7 @@ async function commandHook() {
|
|
|
753
784
|
process.exitCode = 1;
|
|
754
785
|
}
|
|
755
786
|
}
|
|
787
|
+
const promptUsage = `Usage: ocean hook prompt [--client ${PROMPT_HOOK_CLIENTS.join("|")}] (reads a hook payload from stdin)`;
|
|
756
788
|
const sessionEndUsage = `Usage: ocean hook session-end [--client ${SESSION_END_CLIENTS.join("|")}] (reads a hook payload from stdin)`;
|
|
757
789
|
const sessionStartUsage = `Usage: ocean hook session-start [--client ${SESSION_START_CLIENTS.join("|")}] [--repair]|pre-compact (reads a hook payload from stdin)|session-facts --client claude|codex --session <id> --transcript <path>`;
|
|
758
790
|
async function commandIntent() {
|
|
@@ -1016,8 +1048,45 @@ async function commandSkill() {
|
|
|
1016
1048
|
else if (action === "migrate") {
|
|
1017
1049
|
console.log(JSON.stringify(await migrateLegacyLessons(), null, 2));
|
|
1018
1050
|
}
|
|
1051
|
+
else if (action === "route") {
|
|
1052
|
+
// What the prompt hook would name for a message, with the near misses (T-325).
|
|
1053
|
+
const args = process.argv.slice(4);
|
|
1054
|
+
const value = (flag) => {
|
|
1055
|
+
const at = args.indexOf(flag);
|
|
1056
|
+
return at >= 0 ? args[at + 1] : undefined;
|
|
1057
|
+
};
|
|
1058
|
+
const valued = new Set(["--client", "--cwd"]);
|
|
1059
|
+
const message = args
|
|
1060
|
+
.filter((arg, i) => !arg.startsWith("--") && !valued.has(args[i - 1]))
|
|
1061
|
+
.join(" ");
|
|
1062
|
+
if (!message.trim()) {
|
|
1063
|
+
console.error("Usage: ocean skill route <message> [--client claude|codex|gemini|qwen] [--cwd <dir>] [--rebuild] [--json]");
|
|
1064
|
+
process.exitCode = 1;
|
|
1065
|
+
return;
|
|
1066
|
+
}
|
|
1067
|
+
const index = args.includes("--rebuild")
|
|
1068
|
+
? await buildSkillIndex()
|
|
1069
|
+
: await loadSkillIndex();
|
|
1070
|
+
const result = routeSkills(index, message, {
|
|
1071
|
+
signals: await projectSignals(value("--cwd") ?? process.cwd()),
|
|
1072
|
+
client: value("--client") ?? "claude",
|
|
1073
|
+
});
|
|
1074
|
+
if (args.includes("--json"))
|
|
1075
|
+
console.log(JSON.stringify({
|
|
1076
|
+
threshold: ROUTE_THRESHOLD,
|
|
1077
|
+
skills: index.skills.length,
|
|
1078
|
+
...result,
|
|
1079
|
+
}, null, 2));
|
|
1080
|
+
else {
|
|
1081
|
+
console.log(result.matches.length
|
|
1082
|
+
? routerLine(result.matches)
|
|
1083
|
+
: `No skill above the threshold (${ROUTE_THRESHOLD}).`);
|
|
1084
|
+
for (const item of result.candidates)
|
|
1085
|
+
console.log(` ${item.score.toFixed(1).padStart(5)} ${item.name} [${item.why.join(", ")}]`);
|
|
1086
|
+
}
|
|
1087
|
+
}
|
|
1019
1088
|
else {
|
|
1020
|
-
console.error("Usage: ocean skill sync|doctor|list [status|id]|observe [session-id]|add|review <id> promoted|rejected|migrate");
|
|
1089
|
+
console.error("Usage: ocean skill sync|doctor|list [status|id]|observe [session-id]|add|review <id> promoted|rejected|migrate|route <message>");
|
|
1021
1090
|
process.exitCode = 1;
|
|
1022
1091
|
}
|
|
1023
1092
|
}
|