promptlike 0.4.1 → 0.6.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/CHANGELOG.md +44 -0
- package/README.md +134 -2
- package/dist/commands/config.js +41 -0
- package/dist/commands/diff.js +59 -0
- package/dist/commands/export.js +196 -0
- package/dist/commands/history.js +63 -0
- package/dist/commands/import.js +250 -0
- package/dist/commands/list.js +4 -0
- package/dist/commands/log.js +48 -0
- package/dist/commands/rollback.js +88 -0
- package/dist/commands/stats.js +112 -0
- package/dist/commands/suggest.js +244 -0
- package/dist/commands/sync.js +4 -0
- package/dist/index.js +69 -0
- package/dist/lib/agentExport.js +378 -0
- package/dist/lib/api-client.js +91 -8
- package/dist/lib/constants.js +0 -1
- package/dist/lib/diff.js +149 -0
- package/dist/lib/frontmatter.js +67 -0
- package/dist/lib/libraryCache.js +222 -0
- package/dist/lib/promptVariables.js +4 -2
- package/dist/lib/rank.js +123 -0
- package/dist/lib/scanners/index.js +252 -0
- package/dist/lib/secretGuard.js +92 -0
- package/dist/lib/settings.js +105 -0
- package/package.json +1 -1
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
/**
|
|
3
|
+
* Minimal YAML-frontmatter reader for agent files (commands, SKILL.md,
|
|
4
|
+
* `.prompt.md`). Not a YAML parser — agent frontmatter is flat `key: value`
|
|
5
|
+
* lines plus the occasional list (`tags: [a, b]` or `- item` lines), and a
|
|
6
|
+
* full YAML dependency is off-limits for this CLI (commander + chalk only).
|
|
7
|
+
*
|
|
8
|
+
* Anything it cannot understand stays a raw string; nothing throws.
|
|
9
|
+
*/
|
|
10
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
11
|
+
exports.parseFrontmatter = parseFrontmatter;
|
|
12
|
+
function unquote(v) {
|
|
13
|
+
const t = v.trim();
|
|
14
|
+
if ((t.startsWith('"') && t.endsWith('"')) || (t.startsWith("'") && t.endsWith("'"))) {
|
|
15
|
+
return t.slice(1, -1);
|
|
16
|
+
}
|
|
17
|
+
return t;
|
|
18
|
+
}
|
|
19
|
+
function parseFrontmatter(raw) {
|
|
20
|
+
const text = raw.replace(/^/, '').replace(/\r\n/g, '\n');
|
|
21
|
+
const empty = { fields: {}, lists: {}, body: text };
|
|
22
|
+
if (!text.startsWith('---\n'))
|
|
23
|
+
return empty;
|
|
24
|
+
const end = text.indexOf('\n---', 3);
|
|
25
|
+
if (end === -1)
|
|
26
|
+
return empty;
|
|
27
|
+
const header = text.slice(4, end);
|
|
28
|
+
const afterClose = text.slice(end + 4);
|
|
29
|
+
const body = afterClose.replace(/^[^\n]*\n?/, ''); // rest of the closing line
|
|
30
|
+
const fields = {};
|
|
31
|
+
const lists = {};
|
|
32
|
+
let currentListKey = null;
|
|
33
|
+
for (const line of header.split('\n')) {
|
|
34
|
+
const item = line.match(/^\s+-\s+(.*)$/) ?? line.match(/^-\s+(.*)$/);
|
|
35
|
+
if (item && currentListKey) {
|
|
36
|
+
lists[currentListKey].push(unquote(item[1]));
|
|
37
|
+
fields[currentListKey] = lists[currentListKey].join(', ');
|
|
38
|
+
continue;
|
|
39
|
+
}
|
|
40
|
+
const kv = line.match(/^([A-Za-z0-9_-]+):[ \t]*(.*)$/);
|
|
41
|
+
if (!kv) {
|
|
42
|
+
currentListKey = null;
|
|
43
|
+
continue;
|
|
44
|
+
}
|
|
45
|
+
const key = kv[1].toLowerCase();
|
|
46
|
+
const value = kv[2].trim();
|
|
47
|
+
if (value === '') {
|
|
48
|
+
currentListKey = key;
|
|
49
|
+
lists[key] = [];
|
|
50
|
+
fields[key] = '';
|
|
51
|
+
continue;
|
|
52
|
+
}
|
|
53
|
+
currentListKey = null;
|
|
54
|
+
if (value.startsWith('[') && value.endsWith(']')) {
|
|
55
|
+
lists[key] = value
|
|
56
|
+
.slice(1, -1)
|
|
57
|
+
.split(',')
|
|
58
|
+
.map((s) => unquote(s))
|
|
59
|
+
.filter(Boolean);
|
|
60
|
+
fields[key] = lists[key].join(', ');
|
|
61
|
+
}
|
|
62
|
+
else {
|
|
63
|
+
fields[key] = unquote(value);
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
return { fields, lists, body };
|
|
67
|
+
}
|
|
@@ -0,0 +1,222 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
/**
|
|
3
|
+
* Local library cache for suggestions (W1-5) —
|
|
4
|
+
* `~/.config/promptlike/cache/library.json`.
|
|
5
|
+
*
|
|
6
|
+
* Why a cache: the Claude Code `UserPromptSubmit` hook runs before EVERY
|
|
7
|
+
* message and blocks it until it exits, so matching must be local and fast.
|
|
8
|
+
* The user's text never leaves the machine; the cache is refreshed from the
|
|
9
|
+
* account by `ple list` / `ple sync` / `ple suggest`, and in the background
|
|
10
|
+
* (detached, never awaited by the hook) once it is older than 10 minutes.
|
|
11
|
+
*
|
|
12
|
+
* Signed out, suggestions come straight from the local store (`~/.promptlike`)
|
|
13
|
+
* — no cache and no network at all.
|
|
14
|
+
*
|
|
15
|
+
* Also here: per-session "already suggested" memory (the hook never repeats a
|
|
16
|
+
* prompt within one Claude Code session) and the local impression counter
|
|
17
|
+
* `ple stats` shows (impressions stay on this machine; only an accepted
|
|
18
|
+
* suggestion reaches the server, as a `via=suggestion` use).
|
|
19
|
+
*/
|
|
20
|
+
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
|
21
|
+
if (k2 === undefined) k2 = k;
|
|
22
|
+
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
23
|
+
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
24
|
+
desc = { enumerable: true, get: function() { return m[k]; } };
|
|
25
|
+
}
|
|
26
|
+
Object.defineProperty(o, k2, desc);
|
|
27
|
+
}) : (function(o, m, k, k2) {
|
|
28
|
+
if (k2 === undefined) k2 = k;
|
|
29
|
+
o[k2] = m[k];
|
|
30
|
+
}));
|
|
31
|
+
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
|
|
32
|
+
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
|
33
|
+
}) : function(o, v) {
|
|
34
|
+
o["default"] = v;
|
|
35
|
+
});
|
|
36
|
+
var __importStar = (this && this.__importStar) || (function () {
|
|
37
|
+
var ownKeys = function(o) {
|
|
38
|
+
ownKeys = Object.getOwnPropertyNames || function (o) {
|
|
39
|
+
var ar = [];
|
|
40
|
+
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
|
|
41
|
+
return ar;
|
|
42
|
+
};
|
|
43
|
+
return ownKeys(o);
|
|
44
|
+
};
|
|
45
|
+
return function (mod) {
|
|
46
|
+
if (mod && mod.__esModule) return mod;
|
|
47
|
+
var result = {};
|
|
48
|
+
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
|
|
49
|
+
__setModuleDefault(result, mod);
|
|
50
|
+
return result;
|
|
51
|
+
};
|
|
52
|
+
})();
|
|
53
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
54
|
+
exports.CACHE_TTL_MS = void 0;
|
|
55
|
+
exports.cacheDir = cacheDir;
|
|
56
|
+
exports.readCache = readCache;
|
|
57
|
+
exports.isFresh = isFresh;
|
|
58
|
+
exports.entriesFromAccount = entriesFromAccount;
|
|
59
|
+
exports.entriesFromLocal = entriesFromLocal;
|
|
60
|
+
exports.writeCache = writeCache;
|
|
61
|
+
exports.fetchAccountEntries = fetchAccountEntries;
|
|
62
|
+
exports.startBackgroundRefresh = startBackgroundRefresh;
|
|
63
|
+
exports.readState = readState;
|
|
64
|
+
exports.shownIn = shownIn;
|
|
65
|
+
exports.recordShown = recordShown;
|
|
66
|
+
const child_process_1 = require("child_process");
|
|
67
|
+
const fs = __importStar(require("fs"));
|
|
68
|
+
const path = __importStar(require("path"));
|
|
69
|
+
const format_1 = require("./format");
|
|
70
|
+
const rank_1 = require("./rank");
|
|
71
|
+
const settings_1 = require("./settings");
|
|
72
|
+
exports.CACHE_TTL_MS = 10 * 60 * 1000;
|
|
73
|
+
/** Background refreshes are at most one per minute (lock file mtime). */
|
|
74
|
+
const REFRESH_LOCK_MS = 60 * 1000;
|
|
75
|
+
const MAX_SESSIONS = 20;
|
|
76
|
+
/** Library pages fetched for the cache: 5 × 100 = 500 prompts. */
|
|
77
|
+
const MAX_PAGES = 5;
|
|
78
|
+
const PAGE_SIZE = 100;
|
|
79
|
+
function cacheDir() {
|
|
80
|
+
return path.join((0, settings_1.configDir)(), 'cache');
|
|
81
|
+
}
|
|
82
|
+
function cacheFile() {
|
|
83
|
+
return path.join(cacheDir(), 'library.json');
|
|
84
|
+
}
|
|
85
|
+
function writePrivate(file, data) {
|
|
86
|
+
fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 });
|
|
87
|
+
// Write-then-rename: a hook reading mid-write never sees half a file.
|
|
88
|
+
const tmp = `${file}.${process.pid}.tmp`;
|
|
89
|
+
fs.writeFileSync(tmp, JSON.stringify(data), { mode: 0o600 });
|
|
90
|
+
fs.renameSync(tmp, file);
|
|
91
|
+
}
|
|
92
|
+
/** Cached library for `userId`, or null (missing, corrupt, or another account's). */
|
|
93
|
+
function readCache(userId) {
|
|
94
|
+
try {
|
|
95
|
+
const raw = JSON.parse(fs.readFileSync(cacheFile(), 'utf-8'));
|
|
96
|
+
if (raw.v !== 1 || raw.user_id !== userId || !Array.isArray(raw.entries))
|
|
97
|
+
return null;
|
|
98
|
+
return raw;
|
|
99
|
+
}
|
|
100
|
+
catch {
|
|
101
|
+
return null;
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
function isFresh(cache, now = Date.now()) {
|
|
105
|
+
return now - cache.fetched_at < exports.CACHE_TTL_MS;
|
|
106
|
+
}
|
|
107
|
+
function entriesFromAccount(prompts) {
|
|
108
|
+
return prompts.map((p) => ({
|
|
109
|
+
id: p.id,
|
|
110
|
+
name: p.title,
|
|
111
|
+
title: p.title,
|
|
112
|
+
description: p.description ?? null,
|
|
113
|
+
tags: (p.tags ?? []).map((t) => t.name).filter(Boolean),
|
|
114
|
+
body: (0, format_1.joinPromptParts)(p.current_version ?? {}).slice(0, rank_1.BODY_HEAD),
|
|
115
|
+
uses: typeof p.use_count === 'number' ? p.use_count : null,
|
|
116
|
+
repo: p.project_name ?? null,
|
|
117
|
+
}));
|
|
118
|
+
}
|
|
119
|
+
function entriesFromLocal(prompts) {
|
|
120
|
+
return prompts.map((p) => ({
|
|
121
|
+
id: p.slug,
|
|
122
|
+
name: p.slug,
|
|
123
|
+
title: p.title,
|
|
124
|
+
description: p.description || null,
|
|
125
|
+
tags: p.tags,
|
|
126
|
+
body: p.body.slice(0, rank_1.BODY_HEAD),
|
|
127
|
+
uses: null,
|
|
128
|
+
}));
|
|
129
|
+
}
|
|
130
|
+
/** Store a fresh account snapshot. */
|
|
131
|
+
function writeCache(userId, entries, now = Date.now()) {
|
|
132
|
+
const cache = { v: 1, source: 'account', user_id: userId, fetched_at: now, entries };
|
|
133
|
+
writePrivate(cacheFile(), cache);
|
|
134
|
+
return cache;
|
|
135
|
+
}
|
|
136
|
+
/** Fetch the whole library (≤500) page by page. */
|
|
137
|
+
async function fetchAccountEntries(list) {
|
|
138
|
+
const all = [];
|
|
139
|
+
for (let page = 1; page <= MAX_PAGES; page++) {
|
|
140
|
+
const rows = await list({ limit: PAGE_SIZE, page });
|
|
141
|
+
all.push(...rows);
|
|
142
|
+
if (rows.length < PAGE_SIZE)
|
|
143
|
+
break;
|
|
144
|
+
}
|
|
145
|
+
return entriesFromAccount(all);
|
|
146
|
+
}
|
|
147
|
+
const defaultSpawner = (execPath, args) => {
|
|
148
|
+
const child = (0, child_process_1.spawn)(execPath, args, { detached: true, stdio: 'ignore' });
|
|
149
|
+
child.on('error', () => undefined);
|
|
150
|
+
child.unref();
|
|
151
|
+
};
|
|
152
|
+
/**
|
|
153
|
+
* Kick off `ple suggest --refresh-cache` detached (never awaited). At most
|
|
154
|
+
* one per minute unless forced, so a burst of messages does not fork a burst
|
|
155
|
+
* of refreshes. Returns true when a refresh was started.
|
|
156
|
+
*/
|
|
157
|
+
function startBackgroundRefresh(opts = {}) {
|
|
158
|
+
const now = opts.now ?? Date.now();
|
|
159
|
+
const script = process.argv[1];
|
|
160
|
+
if (!script)
|
|
161
|
+
return false;
|
|
162
|
+
const lock = path.join(cacheDir(), 'refresh.lock');
|
|
163
|
+
if (!opts.force) {
|
|
164
|
+
try {
|
|
165
|
+
const age = now - fs.statSync(lock).mtimeMs;
|
|
166
|
+
if (age >= 0 && age < REFRESH_LOCK_MS)
|
|
167
|
+
return false;
|
|
168
|
+
}
|
|
169
|
+
catch {
|
|
170
|
+
// no lock yet
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
try {
|
|
174
|
+
fs.mkdirSync(cacheDir(), { recursive: true, mode: 0o700 });
|
|
175
|
+
fs.writeFileSync(lock, String(now), { mode: 0o600 });
|
|
176
|
+
(opts.spawner ?? defaultSpawner)(process.execPath, [script, 'suggest', '--refresh-cache']);
|
|
177
|
+
return true;
|
|
178
|
+
}
|
|
179
|
+
catch {
|
|
180
|
+
return false;
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
function stateFile() {
|
|
184
|
+
return path.join(cacheDir(), 'suggest-state.json');
|
|
185
|
+
}
|
|
186
|
+
function readState() {
|
|
187
|
+
try {
|
|
188
|
+
const raw = JSON.parse(fs.readFileSync(stateFile(), 'utf-8'));
|
|
189
|
+
return {
|
|
190
|
+
impressions: typeof raw.impressions === 'number' && raw.impressions >= 0 ? raw.impressions : 0,
|
|
191
|
+
sessions: raw.sessions && typeof raw.sessions === 'object' ? raw.sessions : {},
|
|
192
|
+
};
|
|
193
|
+
}
|
|
194
|
+
catch {
|
|
195
|
+
return { impressions: 0, sessions: {} };
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
/** Ids already suggested in this session. */
|
|
199
|
+
function shownIn(state, sessionId) {
|
|
200
|
+
if (!sessionId)
|
|
201
|
+
return new Set();
|
|
202
|
+
return new Set(state.sessions[sessionId]?.shown ?? []);
|
|
203
|
+
}
|
|
204
|
+
/** Record that `ids` were shown: bump the counter, remember them for the session, keep 20 sessions. */
|
|
205
|
+
function recordShown(state, sessionId, ids, now = Date.now()) {
|
|
206
|
+
const sessions = { ...state.sessions };
|
|
207
|
+
if (sessionId) {
|
|
208
|
+
const prev = sessions[sessionId]?.shown ?? [];
|
|
209
|
+
sessions[sessionId] = { at: now, shown: [...new Set([...prev, ...ids])] };
|
|
210
|
+
}
|
|
211
|
+
const kept = Object.entries(sessions)
|
|
212
|
+
.sort((a, b) => b[1].at - a[1].at)
|
|
213
|
+
.slice(0, MAX_SESSIONS);
|
|
214
|
+
const next = { impressions: state.impressions + ids.length, sessions: Object.fromEntries(kept) };
|
|
215
|
+
try {
|
|
216
|
+
writePrivate(stateFile(), next);
|
|
217
|
+
}
|
|
218
|
+
catch {
|
|
219
|
+
// a read-only home must not break the hook
|
|
220
|
+
}
|
|
221
|
+
return next;
|
|
222
|
+
}
|
|
@@ -36,7 +36,9 @@ function fillVariables(text, values) {
|
|
|
36
36
|
if (!text)
|
|
37
37
|
return '';
|
|
38
38
|
return text.replace(VARIABLE_PATTERN, (whole, name) => {
|
|
39
|
-
|
|
40
|
-
|
|
39
|
+
// Yalnız kendi anahtarları: {{constructor}} / {{toString}} gibi adlar
|
|
40
|
+
// Object.prototype'tan fonksiyon çekip metne "function Object()…" basmasın.
|
|
41
|
+
const value = Object.prototype.hasOwnProperty.call(values, name) ? values[name] : undefined;
|
|
42
|
+
return typeof value === 'string' && value !== '' ? value : whole;
|
|
41
43
|
});
|
|
42
44
|
}
|
package/dist/lib/rank.js
ADDED
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
/**
|
|
3
|
+
* Local suggestion ranking for `ple suggest` (W1-5, strategy F3).
|
|
4
|
+
*
|
|
5
|
+
* Pure and dependency-free: runs on the cached library with no network, so
|
|
6
|
+
* the Claude Code hook stays well under its time budget (p95 target 150 ms
|
|
7
|
+
* for 200 prompts — measured in rank.test.ts).
|
|
8
|
+
*
|
|
9
|
+
* Score is BM25-flavoured without the length normalisation (fields are
|
|
10
|
+
* short): Σ over task terms of idf(term) × field weight, where the weight is
|
|
11
|
+
* the best field the term hits — title ×3, tag ×2, description ×1, the first
|
|
12
|
+
* 600 characters of the body ×0.5 — plus a small log bonus for past use.
|
|
13
|
+
*
|
|
14
|
+
* Noise gate (a wrong nudge costs more than a missed one): a prompt qualifies
|
|
15
|
+
* only with a title or tag hit, or with at least two distinct terms matched.
|
|
16
|
+
* Tokenisation and stop words match the server's `src/lib/suggest.ts` so the
|
|
17
|
+
* CLI hook and MCP `suggest_prompts` agree on what a "term" is.
|
|
18
|
+
*/
|
|
19
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
20
|
+
exports.MIN_SCORE = exports.BODY_HEAD = exports.MAX_TERMS = void 0;
|
|
21
|
+
exports.tokenize = tokenize;
|
|
22
|
+
exports.taskTerms = taskTerms;
|
|
23
|
+
exports.rankLibrary = rankLibrary;
|
|
24
|
+
const STOPWORDS = new Set([
|
|
25
|
+
'the', 'and', 'for', 'with', 'this', 'that', 'from', 'into', 'your', 'you', 'are', 'can', 'please',
|
|
26
|
+
'make', 'let', 'use', 'using', 'want', 'need', 'how', 'what', 'why', 'when', 'will', 'should', 'would',
|
|
27
|
+
'bir', 'bu', 've', 'ile', 'için', 'icin', 'şu', 'su', 'gibi', 'daha', 'çok', 'cok', 'olan', 'yap', 'lütfen', 'lutfen',
|
|
28
|
+
]);
|
|
29
|
+
exports.MAX_TERMS = 12;
|
|
30
|
+
/** Body characters considered — the head of a prompt says what it is for. */
|
|
31
|
+
exports.BODY_HEAD = 600;
|
|
32
|
+
/** Minimum score to be suggested at all. */
|
|
33
|
+
exports.MIN_SCORE = 2;
|
|
34
|
+
const WEIGHTS = { title: 3, tag: 2, description: 1, body: 0.5 };
|
|
35
|
+
/** Split text into lower-case word tokens (letters/digits, any script). */
|
|
36
|
+
function tokenize(text) {
|
|
37
|
+
return text
|
|
38
|
+
.toLocaleLowerCase('en-US')
|
|
39
|
+
.normalize('NFKC')
|
|
40
|
+
.split(/[^\p{L}\p{N}]+/u)
|
|
41
|
+
.filter(Boolean);
|
|
42
|
+
}
|
|
43
|
+
/** Task text → distinct search terms (≥3 chars, no stop words, max 12). */
|
|
44
|
+
function taskTerms(task) {
|
|
45
|
+
const words = tokenize(task).filter((w) => w.length >= 3 && !STOPWORDS.has(w));
|
|
46
|
+
return [...new Set(words)].slice(0, exports.MAX_TERMS);
|
|
47
|
+
}
|
|
48
|
+
/**
|
|
49
|
+
* A term hits a field token when one is a prefix of the other and the
|
|
50
|
+
* shorter side has ≥4 chars ("review" ~ "reviews", "refactor" ~ "refactoring"),
|
|
51
|
+
* or when they are equal.
|
|
52
|
+
*/
|
|
53
|
+
function hits(term, tokens) {
|
|
54
|
+
if (tokens.has(term))
|
|
55
|
+
return true;
|
|
56
|
+
for (const t of tokens) {
|
|
57
|
+
const [short, long] = t.length < term.length ? [t, term] : [term, t];
|
|
58
|
+
if (short.length >= 4 && long.startsWith(short))
|
|
59
|
+
return true;
|
|
60
|
+
}
|
|
61
|
+
return false;
|
|
62
|
+
}
|
|
63
|
+
function fieldsOf(item) {
|
|
64
|
+
return {
|
|
65
|
+
title: new Set(tokenize(item.title ?? '')),
|
|
66
|
+
tag: new Set((item.tags ?? []).flatMap((t) => tokenize(t))),
|
|
67
|
+
description: new Set(tokenize(item.description ?? '')),
|
|
68
|
+
body: new Set(tokenize((item.body ?? '').slice(0, exports.BODY_HEAD))),
|
|
69
|
+
};
|
|
70
|
+
}
|
|
71
|
+
/** Rank `items` for `task`; returns at most `limit` items above the noise gate. */
|
|
72
|
+
function rankLibrary(items, task, limit = 3) {
|
|
73
|
+
const terms = taskTerms(task);
|
|
74
|
+
if (terms.length === 0 || items.length === 0)
|
|
75
|
+
return [];
|
|
76
|
+
const fields = items.map(fieldsOf);
|
|
77
|
+
// Document frequency per term over the whole library → idf.
|
|
78
|
+
const n = items.length;
|
|
79
|
+
const idf = new Map();
|
|
80
|
+
for (const term of terms) {
|
|
81
|
+
let df = 0;
|
|
82
|
+
for (const f of fields) {
|
|
83
|
+
if (hits(term, f.title) || hits(term, f.tag) || hits(term, f.description) || hits(term, f.body))
|
|
84
|
+
df++;
|
|
85
|
+
}
|
|
86
|
+
// Smoothed so a 1-prompt library (or a term every prompt shares) still
|
|
87
|
+
// scores a title hit above MIN_SCORE — plain BM25 idf goes to ~0 there.
|
|
88
|
+
idf.set(term, Math.log(1 + (n + 1) / (df + 0.5)));
|
|
89
|
+
}
|
|
90
|
+
const ranked = [];
|
|
91
|
+
items.forEach((item, i) => {
|
|
92
|
+
const f = fields[i];
|
|
93
|
+
let score = 0;
|
|
94
|
+
let strongHit = false;
|
|
95
|
+
let matched = 0;
|
|
96
|
+
for (const term of terms) {
|
|
97
|
+
let w = 0;
|
|
98
|
+
if (hits(term, f.title))
|
|
99
|
+
w = WEIGHTS.title;
|
|
100
|
+
else if (hits(term, f.tag))
|
|
101
|
+
w = WEIGHTS.tag;
|
|
102
|
+
else if (hits(term, f.description))
|
|
103
|
+
w = WEIGHTS.description;
|
|
104
|
+
else if (hits(term, f.body))
|
|
105
|
+
w = WEIGHTS.body;
|
|
106
|
+
if (w === 0)
|
|
107
|
+
continue;
|
|
108
|
+
matched++;
|
|
109
|
+
if (w >= WEIGHTS.tag)
|
|
110
|
+
strongHit = true;
|
|
111
|
+
score += (idf.get(term) ?? 0) * w;
|
|
112
|
+
}
|
|
113
|
+
if (!strongHit && matched < 2)
|
|
114
|
+
return;
|
|
115
|
+
score += Math.log1p(Math.max(0, item.uses ?? 0)) * 0.3;
|
|
116
|
+
if (score < exports.MIN_SCORE)
|
|
117
|
+
return;
|
|
118
|
+
ranked.push({ item, score: Math.round(score * 100) / 100 });
|
|
119
|
+
});
|
|
120
|
+
return ranked
|
|
121
|
+
.sort((a, b) => b.score - a.score || (b.item.uses ?? 0) - (a.item.uses ?? 0))
|
|
122
|
+
.slice(0, Math.max(1, Math.min(limit, 10)));
|
|
123
|
+
}
|
|
@@ -0,0 +1,252 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
/**
|
|
3
|
+
* Agent-file scanners for `ple import --scan` (W1-2 — strategy F15).
|
|
4
|
+
*
|
|
5
|
+
* Finds the reusable instructions a developer already keeps on disk, in the
|
|
6
|
+
* places each agent reads them from:
|
|
7
|
+
*
|
|
8
|
+
* Claude Code ./.claude/commands/**\/*.md ~/.claude/commands/**\/*.md
|
|
9
|
+
* ./.claude/skills/*\/SKILL.md ~/.claude/skills/*\/SKILL.md
|
|
10
|
+
* Cursor ./.cursor/commands/*.md ~/.cursor/commands/*.md
|
|
11
|
+
* Codex ~/.codex/prompts/*.md
|
|
12
|
+
* Copilot ./.github/prompts/*.prompt.md
|
|
13
|
+
* Context ./AGENTS.md ./CLAUDE.md
|
|
14
|
+
*
|
|
15
|
+
* Table-driven: one entry per location, so adding a tool is one line.
|
|
16
|
+
* Every path goes through the secret guard (name check before opening, size
|
|
17
|
+
* check before reading, content check after) — see ./secretGuard.ts.
|
|
18
|
+
* Pure I/O on the local disk; nothing leaves the machine here.
|
|
19
|
+
*/
|
|
20
|
+
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
|
21
|
+
if (k2 === undefined) k2 = k;
|
|
22
|
+
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
23
|
+
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
24
|
+
desc = { enumerable: true, get: function() { return m[k]; } };
|
|
25
|
+
}
|
|
26
|
+
Object.defineProperty(o, k2, desc);
|
|
27
|
+
}) : (function(o, m, k, k2) {
|
|
28
|
+
if (k2 === undefined) k2 = k;
|
|
29
|
+
o[k2] = m[k];
|
|
30
|
+
}));
|
|
31
|
+
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
|
|
32
|
+
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
|
33
|
+
}) : function(o, v) {
|
|
34
|
+
o["default"] = v;
|
|
35
|
+
});
|
|
36
|
+
var __importStar = (this && this.__importStar) || (function () {
|
|
37
|
+
var ownKeys = function(o) {
|
|
38
|
+
ownKeys = Object.getOwnPropertyNames || function (o) {
|
|
39
|
+
var ar = [];
|
|
40
|
+
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
|
|
41
|
+
return ar;
|
|
42
|
+
};
|
|
43
|
+
return ownKeys(o);
|
|
44
|
+
};
|
|
45
|
+
return function (mod) {
|
|
46
|
+
if (mod && mod.__esModule) return mod;
|
|
47
|
+
var result = {};
|
|
48
|
+
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
|
|
49
|
+
__setModuleDefault(result, mod);
|
|
50
|
+
return result;
|
|
51
|
+
};
|
|
52
|
+
})();
|
|
53
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
54
|
+
exports.SCAN_TARGETS = void 0;
|
|
55
|
+
exports.hashBody = hashBody;
|
|
56
|
+
exports.scanAgentFiles = scanAgentFiles;
|
|
57
|
+
const crypto = __importStar(require("crypto"));
|
|
58
|
+
const fs = __importStar(require("fs"));
|
|
59
|
+
const os = __importStar(require("os"));
|
|
60
|
+
const path = __importStar(require("path"));
|
|
61
|
+
const frontmatter_1 = require("../frontmatter");
|
|
62
|
+
const secretGuard_1 = require("../secretGuard");
|
|
63
|
+
exports.SCAN_TARGETS = [
|
|
64
|
+
{ tool: 'claude-code', kind: 'command', root: 'cwd', pattern: { type: 'dir-md', dir: '.claude/commands', recursive: true } },
|
|
65
|
+
{ tool: 'claude-code', kind: 'command', root: 'home', pattern: { type: 'dir-md', dir: '.claude/commands', recursive: true } },
|
|
66
|
+
{ tool: 'claude-code', kind: 'skill', root: 'cwd', pattern: { type: 'skill-dirs', dir: '.claude/skills' } },
|
|
67
|
+
{ tool: 'claude-code', kind: 'skill', root: 'home', pattern: { type: 'skill-dirs', dir: '.claude/skills' } },
|
|
68
|
+
{ tool: 'cursor', kind: 'command', root: 'cwd', pattern: { type: 'dir-md', dir: '.cursor/commands', recursive: false } },
|
|
69
|
+
{ tool: 'cursor', kind: 'command', root: 'home', pattern: { type: 'dir-md', dir: '.cursor/commands', recursive: false } },
|
|
70
|
+
{ tool: 'codex', kind: 'prompt', root: 'home', pattern: { type: 'dir-md', dir: '.codex/prompts', recursive: false } },
|
|
71
|
+
{ tool: 'copilot', kind: 'prompt', root: 'cwd', pattern: { type: 'dir-md', dir: '.github/prompts', recursive: false, suffix: '.prompt.md' } },
|
|
72
|
+
{ tool: 'agents-md', kind: 'context', root: 'cwd', pattern: { type: 'file', file: 'AGENTS.md' } },
|
|
73
|
+
{ tool: 'agents-md', kind: 'context', root: 'cwd', pattern: { type: 'file', file: 'CLAUDE.md' } },
|
|
74
|
+
];
|
|
75
|
+
/** Recursion + volume guards — a scan must stay a one-second operation. */
|
|
76
|
+
const MAX_DEPTH = 4;
|
|
77
|
+
const MAX_FILES = 500;
|
|
78
|
+
const MAX_TAGS = 10;
|
|
79
|
+
const MAX_TITLE = 200;
|
|
80
|
+
const MAX_DESCRIPTION = 1000;
|
|
81
|
+
const KNOWN_KEYS = new Set(['name', 'title', 'description', 'tags']);
|
|
82
|
+
/** Line-ending + surrounding-whitespace insensitive hash of a prompt body. */
|
|
83
|
+
function hashBody(body) {
|
|
84
|
+
const normalized = body.replace(/\r\n/g, '\n').trim();
|
|
85
|
+
return crypto.createHash('sha256').update(normalized, 'utf8').digest('hex');
|
|
86
|
+
}
|
|
87
|
+
function listMdFiles(dir, recursive, suffix, depth = 0) {
|
|
88
|
+
let entries;
|
|
89
|
+
try {
|
|
90
|
+
entries = fs.readdirSync(dir, { withFileTypes: true });
|
|
91
|
+
}
|
|
92
|
+
catch {
|
|
93
|
+
return [];
|
|
94
|
+
}
|
|
95
|
+
const out = [];
|
|
96
|
+
for (const e of entries.sort((a, b) => a.name.localeCompare(b.name))) {
|
|
97
|
+
const full = path.join(dir, e.name);
|
|
98
|
+
if (e.isDirectory()) {
|
|
99
|
+
if (recursive && depth < MAX_DEPTH && !e.name.startsWith('.')) {
|
|
100
|
+
out.push(...listMdFiles(full, recursive, suffix, depth + 1));
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
else if ((e.isFile() || e.isSymbolicLink()) && e.name.toLowerCase().endsWith(suffix)) {
|
|
104
|
+
out.push(full);
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
return out;
|
|
108
|
+
}
|
|
109
|
+
function expand(target, base) {
|
|
110
|
+
const p = target.pattern;
|
|
111
|
+
if (p.type === 'file') {
|
|
112
|
+
const f = path.join(base, p.file);
|
|
113
|
+
return fs.existsSync(f) ? [f] : [];
|
|
114
|
+
}
|
|
115
|
+
if (p.type === 'skill-dirs') {
|
|
116
|
+
const dir = path.join(base, p.dir);
|
|
117
|
+
let entries;
|
|
118
|
+
try {
|
|
119
|
+
entries = fs.readdirSync(dir, { withFileTypes: true });
|
|
120
|
+
}
|
|
121
|
+
catch {
|
|
122
|
+
return [];
|
|
123
|
+
}
|
|
124
|
+
return entries
|
|
125
|
+
.filter((e) => e.isDirectory() || e.isSymbolicLink())
|
|
126
|
+
.map((e) => path.join(dir, e.name, 'SKILL.md'))
|
|
127
|
+
.filter((f) => fs.existsSync(f))
|
|
128
|
+
.sort();
|
|
129
|
+
}
|
|
130
|
+
return listMdFiles(path.join(base, p.dir), p.recursive, p.suffix ?? '.md');
|
|
131
|
+
}
|
|
132
|
+
function titleFor(target, file, base, fmName) {
|
|
133
|
+
if (fmName)
|
|
134
|
+
return fmName;
|
|
135
|
+
const p = target.pattern;
|
|
136
|
+
if (p.type === 'file')
|
|
137
|
+
return `${path.basename(file)} (${path.basename(base)})`;
|
|
138
|
+
if (p.type === 'skill-dirs')
|
|
139
|
+
return path.basename(path.dirname(file));
|
|
140
|
+
const rel = path.relative(path.join(base, p.dir), file).split(path.sep).join('/');
|
|
141
|
+
const suffix = p.suffix ?? '.md';
|
|
142
|
+
return rel.toLowerCase().endsWith(suffix) ? rel.slice(0, -suffix.length) : rel;
|
|
143
|
+
}
|
|
144
|
+
function displayPathFor(file, root, home, cwd) {
|
|
145
|
+
if (root === 'home')
|
|
146
|
+
return `~/${path.relative(home, file).split(path.sep).join('/')}`;
|
|
147
|
+
return path.relative(cwd, file).split(path.sep).join('/');
|
|
148
|
+
}
|
|
149
|
+
/**
|
|
150
|
+
* Read one file through the guard. Returns the raw text, or a skip reason.
|
|
151
|
+
* Symlinks are followed only to a regular `.md` file that also passes the
|
|
152
|
+
* name + size checks, so a link cannot smuggle `~/.ssh/id_rsa` into a scan.
|
|
153
|
+
*/
|
|
154
|
+
function guardedRead(file) {
|
|
155
|
+
if ((0, secretGuard_1.isDeniedFileName)(file))
|
|
156
|
+
return { reason: 'sensitive file name — never read' };
|
|
157
|
+
let real;
|
|
158
|
+
try {
|
|
159
|
+
real = fs.realpathSync(file);
|
|
160
|
+
}
|
|
161
|
+
catch {
|
|
162
|
+
return { reason: 'unreadable' };
|
|
163
|
+
}
|
|
164
|
+
if ((0, secretGuard_1.isDeniedFileName)(real) || !real.toLowerCase().endsWith('.md')) {
|
|
165
|
+
return { reason: 'link to a non-markdown or sensitive file — never read' };
|
|
166
|
+
}
|
|
167
|
+
let stat;
|
|
168
|
+
try {
|
|
169
|
+
stat = fs.statSync(real);
|
|
170
|
+
}
|
|
171
|
+
catch {
|
|
172
|
+
return { reason: 'unreadable' };
|
|
173
|
+
}
|
|
174
|
+
if (!stat.isFile())
|
|
175
|
+
return { reason: 'not a regular file' };
|
|
176
|
+
if (stat.size > secretGuard_1.MAX_SCAN_FILE_BYTES) {
|
|
177
|
+
return { reason: `larger than ${secretGuard_1.MAX_SCAN_FILE_BYTES / 1024} KB — skipped` };
|
|
178
|
+
}
|
|
179
|
+
try {
|
|
180
|
+
return { text: fs.readFileSync(real, 'utf-8'), bytes: stat.size };
|
|
181
|
+
}
|
|
182
|
+
catch {
|
|
183
|
+
return { reason: 'unreadable' };
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
function scanAgentFiles(options = {}) {
|
|
187
|
+
const cwd = path.resolve(options.cwd ?? process.cwd());
|
|
188
|
+
const home = path.resolve(options.home ?? os.homedir());
|
|
189
|
+
const candidates = [];
|
|
190
|
+
const skipped = [];
|
|
191
|
+
const duplicates = [];
|
|
192
|
+
const seenFiles = new Set();
|
|
193
|
+
const seenHashes = new Set();
|
|
194
|
+
let fileCount = 0;
|
|
195
|
+
scan: for (const target of exports.SCAN_TARGETS) {
|
|
196
|
+
const base = target.root === 'home' ? home : cwd;
|
|
197
|
+
// When cwd IS home, project and home targets overlap — scan once.
|
|
198
|
+
for (const file of expand(target, base)) {
|
|
199
|
+
const key = path.resolve(file);
|
|
200
|
+
if (seenFiles.has(key))
|
|
201
|
+
continue;
|
|
202
|
+
seenFiles.add(key);
|
|
203
|
+
if (++fileCount > MAX_FILES) {
|
|
204
|
+
skipped.push({ displayPath: displayPathFor(file, target.root, home, cwd), reason: `scan capped at ${MAX_FILES} files` });
|
|
205
|
+
break scan;
|
|
206
|
+
}
|
|
207
|
+
const displayPath = displayPathFor(file, target.root, home, cwd);
|
|
208
|
+
const read = guardedRead(file);
|
|
209
|
+
if ('reason' in read) {
|
|
210
|
+
skipped.push({ displayPath, reason: read.reason });
|
|
211
|
+
continue;
|
|
212
|
+
}
|
|
213
|
+
const secret = (0, secretGuard_1.findSecret)(read.text);
|
|
214
|
+
if (secret) {
|
|
215
|
+
skipped.push({ displayPath, reason: `looks like it contains a ${secret} — remove it, then re-run` });
|
|
216
|
+
continue;
|
|
217
|
+
}
|
|
218
|
+
const fm = (0, frontmatter_1.parseFrontmatter)(read.text);
|
|
219
|
+
const body = fm.body.trim();
|
|
220
|
+
if (!body) {
|
|
221
|
+
skipped.push({ displayPath, reason: 'empty body' });
|
|
222
|
+
continue;
|
|
223
|
+
}
|
|
224
|
+
const fmTags = fm.lists.tags ?? (fm.fields.tags ? fm.fields.tags.split(',') : []);
|
|
225
|
+
const tags = [...new Set([...fmTags.map((t) => t.trim()).filter(Boolean), target.tool])].slice(0, MAX_TAGS);
|
|
226
|
+
const meta = {};
|
|
227
|
+
for (const [k, v] of Object.entries(fm.fields)) {
|
|
228
|
+
if (!KNOWN_KEYS.has(k) && v)
|
|
229
|
+
meta[k] = v;
|
|
230
|
+
}
|
|
231
|
+
const candidate = {
|
|
232
|
+
tool: target.tool,
|
|
233
|
+
kind: target.kind,
|
|
234
|
+
displayPath,
|
|
235
|
+
title: titleFor(target, file, base, fm.fields.name || fm.fields.title || '').slice(0, MAX_TITLE),
|
|
236
|
+
description: (fm.fields.description ?? '').slice(0, MAX_DESCRIPTION),
|
|
237
|
+
tags,
|
|
238
|
+
body,
|
|
239
|
+
meta,
|
|
240
|
+
bytes: read.bytes,
|
|
241
|
+
sha256: hashBody(body),
|
|
242
|
+
};
|
|
243
|
+
if (seenHashes.has(candidate.sha256)) {
|
|
244
|
+
duplicates.push(candidate);
|
|
245
|
+
continue;
|
|
246
|
+
}
|
|
247
|
+
seenHashes.add(candidate.sha256);
|
|
248
|
+
candidates.push(candidate);
|
|
249
|
+
}
|
|
250
|
+
}
|
|
251
|
+
return { candidates, skipped, duplicates };
|
|
252
|
+
}
|