@event4u/agent-config 8.6.0 → 8.7.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/.claude-plugin/marketplace.json +1 -1
- package/CHANGELOG.md +29 -0
- package/dist/agent-src/skills/skill-writing/SKILL.md +4 -0
- package/dist/agent-src/templates/agents/agent-project-settings.example.yml +1 -1
- package/dist/discovery/deprecation-report.md +1 -1
- package/dist/discovery/discovery-manifest.json +3 -3
- package/dist/discovery/discovery-manifest.json.sha256 +1 -1
- package/dist/discovery/discovery-manifest.summary.md +1 -1
- package/dist/discovery/orphan-report.md +1 -1
- package/dist/discovery/packs.json +2 -2
- package/dist/discovery/trust-report.md +1 -1
- package/dist/discovery/workspaces.json +2 -2
- package/dist/install/emit_host_rules_cli.js +185 -0
- package/dist/install/emit_host_rules_cli.js.map +1 -0
- package/dist/install/install.mjs +6 -0
- package/dist/install/plan.js +4 -1
- package/dist/install/plan.js.map +1 -1
- package/dist/install/rule_scope.js +109 -0
- package/dist/install/rule_scope.js.map +1 -0
- package/dist/install/rule_scope_cli.js +77 -0
- package/dist/install/rule_scope_cli.js.map +1 -0
- package/dist/install/wizard-plan.js +14 -1
- package/dist/install/wizard-plan.js.map +1 -1
- package/dist/mcp/registry-manifest.json +1 -1
- package/dist/scripts/_lib/agent_settings.js +963 -0
- package/dist/scripts/_lib/agent_settings.js.map +1 -0
- package/dist/scripts/_lib/agent_src.js +607 -0
- package/dist/scripts/_lib/agent_src.js.map +1 -0
- package/dist/scripts/_lib/claude_settings_hooks.js +209 -0
- package/dist/scripts/_lib/claude_settings_hooks.js.map +1 -0
- package/dist/scripts/_lib/model_tier.js +64 -0
- package/dist/scripts/_lib/model_tier.js.map +1 -0
- package/dist/scripts/_lib/script_output.js +140 -0
- package/dist/scripts/_lib/script_output.js.map +1 -0
- package/dist/scripts/_lib/user_global_paths.js +297 -0
- package/dist/scripts/_lib/user_global_paths.js.map +1 -0
- package/dist/scripts/condense.js +2181 -0
- package/dist/scripts/condense.js.map +1 -0
- package/dist/server/routes/install.js +18 -2
- package/dist/server/routes/install.js.map +1 -1
- package/dist/server/schemas/settings.js +2 -0
- package/dist/server/schemas/settings.js.map +1 -1
- package/package.json +1 -1
- package/src/config/agent-settings.template.yml +4 -2
- package/src/install/emit_host_rules_cli.ts +190 -0
- package/src/install/plan.ts +11 -1
- package/src/install/rule_scope.ts +120 -0
- package/src/install/rule_scope_cli.ts +79 -0
- package/src/install/wizard-plan.ts +22 -1
- package/src/scripts/check_trigger_eval_presence.ts +171 -0
- package/src/scripts/install.sh +118 -4
- package/src/scripts/trigger_eval_grandfather.json +226 -0
- package/src/server/schemas/settings.ts +6 -0
|
@@ -0,0 +1,2181 @@
|
|
|
1
|
+
#!/usr/bin/env tsx
|
|
2
|
+
/**
|
|
3
|
+
* Agent-config sync — condense .agent-src.uncondensed/ → dist/agent-src/
|
|
4
|
+
* and project dist/agent-src/ → .augment/ (copies for rules by default,
|
|
5
|
+
* symlinks for the rest; opt into rule symlinks via
|
|
6
|
+
* augment.rules_use_symlinks in .agent-settings.yml).
|
|
7
|
+
*
|
|
8
|
+
* Ported from the retired Python `src/scripts/condense.py` (ADR-200 — Python→TS
|
|
9
|
+
* migration, Phase 5). Mirrors the Python CLI surface EXACTLY — every
|
|
10
|
+
* subcommand (`--sync`, `--list`, `--changed`, `--check`, `--check-hashes`,
|
|
11
|
+
* `--clean-hashes`, `--mark-done <path>`, `--mark-all-done`,
|
|
12
|
+
* `--generate-tools`, `--clean-tools`, `--project-augment`) — same flags,
|
|
13
|
+
* exit codes, stdout/stderr split, byte-identical messages. No behaviour
|
|
14
|
+
* changes; historical quirks preserved and flagged.
|
|
15
|
+
*
|
|
16
|
+
* Path handling note: the retired Python implementation uses `pathlib.Path` objects.
|
|
17
|
+
* This twin uses absolute path strings (the host filesystem on the
|
|
18
|
+
* supported platforms is POSIX). Logical relative paths are always POSIX
|
|
19
|
+
* (forward-slash) strings, matching the Python `.as_posix()` keys.
|
|
20
|
+
*
|
|
21
|
+
* Module-level constants (PROJECT_ROOT, SOURCE_DIR, TARGET_DIR, …) and the
|
|
22
|
+
* multi-root helper functions (iter_all_sources, resolve_logical,
|
|
23
|
+
* artefact_roots) are exposed through a mutable module-state object so the
|
|
24
|
+
* pytest suite's monkeypatch pattern — reassigning `condense.PROJECT_ROOT`,
|
|
25
|
+
* `condense.HASH_FILE`, `condense.iter_all_sources`, … — has a faithful TS
|
|
26
|
+
* equivalent. Tests mutate `MODULE_STATE` via the exported setters.
|
|
27
|
+
*/
|
|
28
|
+
import * as crypto from 'node:crypto';
|
|
29
|
+
import * as fs from 'node:fs';
|
|
30
|
+
import * as path from 'node:path';
|
|
31
|
+
import { fileURLToPath, pathToFileURL } from 'node:url';
|
|
32
|
+
import * as YAML from 'yaml';
|
|
33
|
+
import { artefact_roots as _agent_src_artefact_roots, iter_all_sources as _agent_src_iter_all_sources, resolve_logical as _agent_src_resolve_logical, strip_source_prefix, } from './_lib/agent_src.js';
|
|
34
|
+
import { build_claude_hook_matrix } from './_lib/claude_settings_hooks.js';
|
|
35
|
+
import { project_settings_path, load_agent_settings } from './_lib/agent_settings.js';
|
|
36
|
+
import { info, success, flush_summary, resolve_level } from './_lib/script_output.js';
|
|
37
|
+
import { TIER_TO_CLAUDE_MODEL as _TIER_TO_CLAUDE_MODEL, MODEL_TIER_RE as _MODEL_TIER_RE, } from './_lib/model_tier.js';
|
|
38
|
+
// The Python module imports `_SLUG_PREFIX_RE` from `_lib.agent_src`. The TS
|
|
39
|
+
// twin does not re-export that private regex, so reproduce it locally — it is
|
|
40
|
+
// only used by `_domains_slug_prefix` below (PROJECT_ROOT-aware mirror).
|
|
41
|
+
const _SLUG_PREFIX_RE = /^slug_prefix:\s*"?([a-z][a-z0-9-]*)"?\s*$/m;
|
|
42
|
+
/**
|
|
43
|
+
* Best-effort YAML parse mirroring Python's `yaml.safe_load` tolerance.
|
|
44
|
+
* Returns `null` on any parse failure (callers treat that as "no data").
|
|
45
|
+
* version '1.1' matches PyYAML's bool/int quirks so frontmatter parses
|
|
46
|
+
* identically. A STATIC import (not a lazy `require`) — `require` is not
|
|
47
|
+
* reliably available under ESM/tsx, which silently degraded dependency
|
|
48
|
+
* folding to a plain file hash when condense.ts ran as the main module.
|
|
49
|
+
*/
|
|
50
|
+
function _yamlParse(text) {
|
|
51
|
+
try {
|
|
52
|
+
const data = YAML.parse(text, { version: '1.1' });
|
|
53
|
+
return data === undefined ? null : data;
|
|
54
|
+
}
|
|
55
|
+
catch {
|
|
56
|
+
return null;
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
// --- Filesystem helpers reproducing pathlib semantics ------------------------
|
|
60
|
+
function _exists(p) {
|
|
61
|
+
try {
|
|
62
|
+
fs.lstatSync(p);
|
|
63
|
+
fs.statSync(p);
|
|
64
|
+
return true;
|
|
65
|
+
}
|
|
66
|
+
catch {
|
|
67
|
+
return false;
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
/** Path.exists() OR Path.is_symlink() — true even for a broken symlink. */
|
|
71
|
+
function _existsOrSymlink(p) {
|
|
72
|
+
try {
|
|
73
|
+
fs.lstatSync(p);
|
|
74
|
+
return true;
|
|
75
|
+
}
|
|
76
|
+
catch {
|
|
77
|
+
return false;
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
function _isDir(p) {
|
|
81
|
+
try {
|
|
82
|
+
return fs.statSync(p).isDirectory();
|
|
83
|
+
}
|
|
84
|
+
catch {
|
|
85
|
+
return false;
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
function _isFile(p) {
|
|
89
|
+
try {
|
|
90
|
+
return fs.statSync(p).isFile();
|
|
91
|
+
}
|
|
92
|
+
catch {
|
|
93
|
+
return false;
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
function _isSymlink(p) {
|
|
97
|
+
try {
|
|
98
|
+
return fs.lstatSync(p).isSymbolicLink();
|
|
99
|
+
}
|
|
100
|
+
catch {
|
|
101
|
+
return false;
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
/** `Path.is_dir()` that does NOT follow a symlink (lstat-based). */
|
|
105
|
+
function _isDirNoFollow(p) {
|
|
106
|
+
try {
|
|
107
|
+
return fs.lstatSync(p).isDirectory();
|
|
108
|
+
}
|
|
109
|
+
catch {
|
|
110
|
+
return false;
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
function _readText(p) {
|
|
114
|
+
return fs.readFileSync(p, 'utf-8');
|
|
115
|
+
}
|
|
116
|
+
function _writeText(p, text) {
|
|
117
|
+
fs.writeFileSync(p, text, 'utf-8');
|
|
118
|
+
}
|
|
119
|
+
function _mkdirp(p) {
|
|
120
|
+
fs.mkdirSync(p, { recursive: true });
|
|
121
|
+
}
|
|
122
|
+
/** Sorted immediate children as absolute paths (mirrors sorted(p.iterdir())). */
|
|
123
|
+
function _iterdirSorted(p) {
|
|
124
|
+
let names;
|
|
125
|
+
try {
|
|
126
|
+
names = fs.readdirSync(p);
|
|
127
|
+
}
|
|
128
|
+
catch {
|
|
129
|
+
return [];
|
|
130
|
+
}
|
|
131
|
+
names.sort((a, b) => (a < b ? -1 : a > b ? 1 : 0));
|
|
132
|
+
return names.map((n) => path.join(p, n));
|
|
133
|
+
}
|
|
134
|
+
/**
|
|
135
|
+
* Mirror `root.rglob(pattern)` → SORTED absolute path strings. Yields every
|
|
136
|
+
* descendant (files AND dirs) whose name matches; callers sort, so sort here
|
|
137
|
+
* by the POSIX-string key Python uses. `pattern` is `"*"` or a `"*<suffix>"`
|
|
138
|
+
* suffix glob.
|
|
139
|
+
*/
|
|
140
|
+
function _rglobSorted(root, pattern) {
|
|
141
|
+
const out = [];
|
|
142
|
+
const suffix = pattern === '*' ? null : pattern.slice(1);
|
|
143
|
+
const walk = (dir) => {
|
|
144
|
+
let entries;
|
|
145
|
+
try {
|
|
146
|
+
entries = fs.readdirSync(dir, { withFileTypes: true });
|
|
147
|
+
}
|
|
148
|
+
catch {
|
|
149
|
+
return;
|
|
150
|
+
}
|
|
151
|
+
for (const ent of entries) {
|
|
152
|
+
const full = path.join(dir, ent.name);
|
|
153
|
+
const matches = suffix === null ? true : ent.name.endsWith(suffix);
|
|
154
|
+
if (matches) {
|
|
155
|
+
out.push(full);
|
|
156
|
+
}
|
|
157
|
+
if (ent.isDirectory() || (ent.isSymbolicLink() && _isDir(full))) {
|
|
158
|
+
walk(full);
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
};
|
|
162
|
+
walk(root);
|
|
163
|
+
out.sort((a, b) => (a < b ? -1 : a > b ? 1 : 0));
|
|
164
|
+
return out;
|
|
165
|
+
}
|
|
166
|
+
function _relativeToPosix(child, root) {
|
|
167
|
+
const rel = path.relative(root, child);
|
|
168
|
+
return rel.split(path.sep).join('/');
|
|
169
|
+
}
|
|
170
|
+
function _isUnder(child, root) {
|
|
171
|
+
const rel = path.relative(root, child);
|
|
172
|
+
return rel !== '' && !rel.startsWith('..') && !path.isAbsolute(rel);
|
|
173
|
+
}
|
|
174
|
+
/** POSIX `parts` of a path string, dropping empty segments (mirrors Path.parts). */
|
|
175
|
+
function _posixParts(p) {
|
|
176
|
+
return p.split('/').filter((s) => s.length > 0);
|
|
177
|
+
}
|
|
178
|
+
/** Python str.lstrip() with no args — strip leading Unicode whitespace. */
|
|
179
|
+
function _lstrip(s) {
|
|
180
|
+
return s.replace(/^\s+/u, '');
|
|
181
|
+
}
|
|
182
|
+
/** Python str.strip() with no args — strip leading/trailing Unicode whitespace. */
|
|
183
|
+
function _strip(s) {
|
|
184
|
+
return s.replace(/^\s+/u, '').replace(/\s+$/u, '');
|
|
185
|
+
}
|
|
186
|
+
/** Python str.lstrip("\n") — strip only leading newlines. */
|
|
187
|
+
function _lstripNewlines(s) {
|
|
188
|
+
return s.replace(/^\n+/, '');
|
|
189
|
+
}
|
|
190
|
+
/** Python `.strip('"').strip("'")` — strip the given chars from both ends. */
|
|
191
|
+
function _stripChars(s, chars) {
|
|
192
|
+
let start = 0;
|
|
193
|
+
let end = s.length;
|
|
194
|
+
while (start < end && chars.includes(s[start]))
|
|
195
|
+
start += 1;
|
|
196
|
+
while (end > start && chars.includes(s[end - 1]))
|
|
197
|
+
end -= 1;
|
|
198
|
+
return s.slice(start, end);
|
|
199
|
+
}
|
|
200
|
+
// =============================================================================
|
|
201
|
+
// Module state — mutable mirror of the Python module-level constants & hooks.
|
|
202
|
+
//
|
|
203
|
+
// The pytest suite reassigns `condense.PROJECT_ROOT`, `condense.HASH_FILE`,
|
|
204
|
+
// `condense.TARGET_DIR`, `condense.SOURCE_DIR`, `condense.RULES_SOURCE`,
|
|
205
|
+
// `condense.SKILLS_SOURCE`, `condense.COMMANDS_SOURCE`,
|
|
206
|
+
// `condense.CLAUDE_SKILLS_DIR`, `condense.AUGMENT_DIR`, `condense.SETTINGS_FILE`,
|
|
207
|
+
// and the helper functions `condense.iter_all_sources`,
|
|
208
|
+
// `condense.resolve_logical`, `condense.artefact_roots`. All such state lives
|
|
209
|
+
// here so TS tests can inject the same way via the exported setters.
|
|
210
|
+
//
|
|
211
|
+
// PROJECT_ROOT default: Path(__file__).resolve().parent.parent.parent — the
|
|
212
|
+
// .py file lives at <repo>/src/scripts/condense.py, so three parents up is
|
|
213
|
+
// the repo root.
|
|
214
|
+
// =============================================================================
|
|
215
|
+
const _HERE = path.dirname(fileURLToPath(import.meta.url)); // <repo>/src/scripts
|
|
216
|
+
const _DEFAULT_PROJECT_ROOT = path.resolve(_HERE, '..', '..');
|
|
217
|
+
function _deriveState(root) {
|
|
218
|
+
return {
|
|
219
|
+
PROJECT_ROOT: root,
|
|
220
|
+
SOURCE_DIR: path.join(root, '.agent-src.uncondensed'),
|
|
221
|
+
TARGET_DIR: path.join(root, 'dist/agent-src'),
|
|
222
|
+
AUGMENT_DIR: path.join(root, '.augment'),
|
|
223
|
+
HASH_FILE: path.join(root, 'internal', '.condensation-hashes.json'),
|
|
224
|
+
SETTINGS_FILE: project_settings_path(root),
|
|
225
|
+
RULES_SOURCE: path.join(root, 'dist/agent-src', 'rules'),
|
|
226
|
+
SKILLS_SOURCE: path.join(root, 'dist/agent-src', 'skills'),
|
|
227
|
+
COMMANDS_SOURCE: path.join(root, 'dist/agent-src', 'commands'),
|
|
228
|
+
PERSONAS_SOURCE: path.join(root, 'dist/agent-src', 'personas'),
|
|
229
|
+
USER_TYPES_SOURCE: path.join(root, 'dist/agent-src', 'user-types'),
|
|
230
|
+
CLAUDE_SKILLS_DIR: path.join(root, '.claude', 'skills'),
|
|
231
|
+
// ADR-109: subagents project from src/ directly (NOT dist/) — a subagent
|
|
232
|
+
// is an executable system prompt Claude Code runs verbatim; telegraph
|
|
233
|
+
// condensation would alter its behaviour, and it is not routed through the
|
|
234
|
+
// pack/discovery condensation flow.
|
|
235
|
+
CLAUDE_AGENTS_DIR: path.join(root, '.claude', 'agents'),
|
|
236
|
+
SUBAGENTS_SOURCE: path.join(root, 'src', 'subagents'),
|
|
237
|
+
PLUGIN_SKILLS_DIR: path.join(root, '.claude-plugin', 'skills'),
|
|
238
|
+
iter_all_sources: _agent_src_iter_all_sources,
|
|
239
|
+
resolve_logical: _agent_src_resolve_logical,
|
|
240
|
+
artefact_roots: _agent_src_artefact_roots,
|
|
241
|
+
};
|
|
242
|
+
}
|
|
243
|
+
export const MODULE_STATE = _deriveState(_DEFAULT_PROJECT_ROOT);
|
|
244
|
+
/**
|
|
245
|
+
* Test seam — reassign one or more module-state fields, mirroring the pytest
|
|
246
|
+
* monkeypatch of `condense.<NAME> = ...`. When `PROJECT_ROOT` is overridden,
|
|
247
|
+
* SETTINGS_FILE is NOT recomputed (Python tests set it explicitly when they
|
|
248
|
+
* need it) — only the literally-supplied keys change. Not part of the Python
|
|
249
|
+
* surface; a TS-only injection point.
|
|
250
|
+
*/
|
|
251
|
+
export function _setStateForTest(overrides) {
|
|
252
|
+
Object.assign(MODULE_STATE, overrides);
|
|
253
|
+
}
|
|
254
|
+
/** Snapshot module state for save/restore in tests. */
|
|
255
|
+
export function _getStateForTest() {
|
|
256
|
+
return { ...MODULE_STATE };
|
|
257
|
+
}
|
|
258
|
+
/**
|
|
259
|
+
* Re-derive ALL module-state fields from a fresh PROJECT_ROOT (mirrors the
|
|
260
|
+
* Python convention where every constant is recomputed from PROJECT_ROOT).
|
|
261
|
+
* Convenience for tests that want a clean tmp-root layout.
|
|
262
|
+
*/
|
|
263
|
+
export function _resetStateForTest(root = _DEFAULT_PROJECT_ROOT) {
|
|
264
|
+
Object.assign(MODULE_STATE, _deriveState(root));
|
|
265
|
+
}
|
|
266
|
+
// Convenience accessors used internally — read through MODULE_STATE so a test
|
|
267
|
+
// override is always honoured.
|
|
268
|
+
function _iter_sources() {
|
|
269
|
+
// Wraps the injectable iter_all_sources hook (mirrors condense._iter_sources).
|
|
270
|
+
return MODULE_STATE.iter_all_sources();
|
|
271
|
+
}
|
|
272
|
+
function _resolve_source(relative) {
|
|
273
|
+
return MODULE_STATE.resolve_logical(relative);
|
|
274
|
+
}
|
|
275
|
+
function _any_source_root_exists() {
|
|
276
|
+
return [...MODULE_STATE.artefact_roots()].length > 0;
|
|
277
|
+
}
|
|
278
|
+
// --- Self-projection tool toggle ---------------------------------------------
|
|
279
|
+
const _ALL_TOOLS = new Set([
|
|
280
|
+
'claude-code',
|
|
281
|
+
'claude-desktop',
|
|
282
|
+
'augment',
|
|
283
|
+
'copilot',
|
|
284
|
+
'cursor',
|
|
285
|
+
'windsurf',
|
|
286
|
+
'cline',
|
|
287
|
+
'gemini',
|
|
288
|
+
]);
|
|
289
|
+
void _ALL_TOOLS;
|
|
290
|
+
function _active_tools() {
|
|
291
|
+
const tools_file = path.join(MODULE_STATE.PROJECT_ROOT, 'agents', '.agent-tools.yml');
|
|
292
|
+
if (!_exists(tools_file)) {
|
|
293
|
+
return null;
|
|
294
|
+
}
|
|
295
|
+
// Mirrors Python's `yaml.safe_load`; a malformed file → YAMLError → null
|
|
296
|
+
// (treated as "all tools").
|
|
297
|
+
let data = _yamlParse(_readText(tools_file));
|
|
298
|
+
if (data === null || data === undefined) {
|
|
299
|
+
data = {};
|
|
300
|
+
}
|
|
301
|
+
const tools = typeof data === 'object' && data !== null && !Array.isArray(data)
|
|
302
|
+
? data['tools']
|
|
303
|
+
: null;
|
|
304
|
+
if (!Array.isArray(tools)) {
|
|
305
|
+
return null;
|
|
306
|
+
}
|
|
307
|
+
return new Set(tools.filter((t) => typeof t === 'string'));
|
|
308
|
+
}
|
|
309
|
+
function _tool_active(tool_id) {
|
|
310
|
+
const active = _active_tools();
|
|
311
|
+
return active === null ? true : active.has(tool_id);
|
|
312
|
+
}
|
|
313
|
+
// Files to copy as-is even if .md (not condensed by agent).
|
|
314
|
+
const COPY_AS_IS = new Set(['README.md']);
|
|
315
|
+
// Directories whose .md content is data, not prose — copied verbatim.
|
|
316
|
+
const COPY_AS_IS_DIRS = new Set(['ghostwriter']);
|
|
317
|
+
// --- settings readers --------------------------------------------------------
|
|
318
|
+
function _read_augment_rules_use_symlinks() {
|
|
319
|
+
const data = load_agent_settings({ project_path: MODULE_STATE.SETTINGS_FILE });
|
|
320
|
+
const augment = data['augment'];
|
|
321
|
+
if (typeof augment !== 'object' || augment === null || Array.isArray(augment)) {
|
|
322
|
+
return false;
|
|
323
|
+
}
|
|
324
|
+
const value = augment['rules_use_symlinks'];
|
|
325
|
+
if (typeof value === 'boolean') {
|
|
326
|
+
return value;
|
|
327
|
+
}
|
|
328
|
+
if (typeof value === 'string') {
|
|
329
|
+
return ['true', 'yes', 'on', '1'].includes(value.trim().toLowerCase());
|
|
330
|
+
}
|
|
331
|
+
if (typeof value === 'number') {
|
|
332
|
+
return value === 1;
|
|
333
|
+
}
|
|
334
|
+
return false;
|
|
335
|
+
}
|
|
336
|
+
function _lean_projection_mode() {
|
|
337
|
+
const data = load_agent_settings({ project_path: MODULE_STATE.SETTINGS_FILE });
|
|
338
|
+
const lean = data['lean_projection'];
|
|
339
|
+
if (typeof lean === 'object' &&
|
|
340
|
+
lean !== null &&
|
|
341
|
+
!Array.isArray(lean) &&
|
|
342
|
+
String(lean['mode'] ?? '')
|
|
343
|
+
.trim()
|
|
344
|
+
.toLowerCase() === 'thin') {
|
|
345
|
+
return 'thin';
|
|
346
|
+
}
|
|
347
|
+
return 'eager-all';
|
|
348
|
+
}
|
|
349
|
+
// --- hashing -----------------------------------------------------------------
|
|
350
|
+
export function file_hash(filepath) {
|
|
351
|
+
const h = crypto.createHash('sha256');
|
|
352
|
+
h.update(fs.readFileSync(filepath));
|
|
353
|
+
return h.digest('hex');
|
|
354
|
+
}
|
|
355
|
+
const _DEP_FRONTMATTER_KEYS = ['skills', 'rules'];
|
|
356
|
+
function _slug_to_logical(slug) {
|
|
357
|
+
for (const cand of [`skills/${slug}/SKILL.md`, `rules/${slug}.md`]) {
|
|
358
|
+
if (_resolve_source(cand) !== null) {
|
|
359
|
+
return cand;
|
|
360
|
+
}
|
|
361
|
+
}
|
|
362
|
+
return null;
|
|
363
|
+
}
|
|
364
|
+
function _direct_includes(relative) {
|
|
365
|
+
const source = _resolve_source(relative);
|
|
366
|
+
if (source === null) {
|
|
367
|
+
return [];
|
|
368
|
+
}
|
|
369
|
+
let meta;
|
|
370
|
+
try {
|
|
371
|
+
[meta] = _parse_frontmatter(_readText(source));
|
|
372
|
+
}
|
|
373
|
+
catch {
|
|
374
|
+
return [];
|
|
375
|
+
}
|
|
376
|
+
const deps = [];
|
|
377
|
+
for (const key of _DEP_FRONTMATTER_KEYS) {
|
|
378
|
+
const value = meta[key];
|
|
379
|
+
if (!Array.isArray(value)) {
|
|
380
|
+
continue;
|
|
381
|
+
}
|
|
382
|
+
for (const item of value) {
|
|
383
|
+
if (typeof item !== 'string') {
|
|
384
|
+
continue;
|
|
385
|
+
}
|
|
386
|
+
const logical = _slug_to_logical(item.trim());
|
|
387
|
+
if (logical !== null && logical !== relative) {
|
|
388
|
+
deps.push(logical);
|
|
389
|
+
}
|
|
390
|
+
}
|
|
391
|
+
}
|
|
392
|
+
return deps;
|
|
393
|
+
}
|
|
394
|
+
export function effective_hash(relative, _seen = null) {
|
|
395
|
+
const source = _resolve_source(relative);
|
|
396
|
+
if (source === null) {
|
|
397
|
+
return '';
|
|
398
|
+
}
|
|
399
|
+
const own = file_hash(source);
|
|
400
|
+
if (_seen !== null && _seen.has(relative)) {
|
|
401
|
+
return own; // cycle — fold own content only
|
|
402
|
+
}
|
|
403
|
+
const deps = [...new Set(_direct_includes(relative))].sort((a, b) => a < b ? -1 : a > b ? 1 : 0);
|
|
404
|
+
if (deps.length === 0) {
|
|
405
|
+
return own; // leaf — identical to plain file_hash
|
|
406
|
+
}
|
|
407
|
+
const seenNext = new Set(_seen ?? []);
|
|
408
|
+
seenNext.add(relative);
|
|
409
|
+
const parts = [own, ...deps.map((dep) => effective_hash(dep, seenNext))];
|
|
410
|
+
return crypto.createHash('sha256').update(parts.join('\n'), 'utf-8').digest('hex');
|
|
411
|
+
}
|
|
412
|
+
export function load_hashes() {
|
|
413
|
+
if (_exists(MODULE_STATE.HASH_FILE)) {
|
|
414
|
+
try {
|
|
415
|
+
return JSON.parse(_readText(MODULE_STATE.HASH_FILE));
|
|
416
|
+
}
|
|
417
|
+
catch {
|
|
418
|
+
return {};
|
|
419
|
+
}
|
|
420
|
+
}
|
|
421
|
+
return {};
|
|
422
|
+
}
|
|
423
|
+
export function save_hashes(hashes) {
|
|
424
|
+
_mkdirp(path.dirname(MODULE_STATE.HASH_FILE));
|
|
425
|
+
_writeText(MODULE_STATE.HASH_FILE, _jsonDumpsSorted(hashes) + '\n');
|
|
426
|
+
}
|
|
427
|
+
/** Mirror json.dumps(obj, indent=2, sort_keys=True) for a flat string map. */
|
|
428
|
+
function _jsonDumpsSorted(obj) {
|
|
429
|
+
const keys = Object.keys(obj).sort((a, b) => (a < b ? -1 : a > b ? 1 : 0));
|
|
430
|
+
if (keys.length === 0) {
|
|
431
|
+
return '{}';
|
|
432
|
+
}
|
|
433
|
+
const lines = keys.map((k) => ` ${JSON.stringify(k)}: ${JSON.stringify(obj[k])}`);
|
|
434
|
+
return `{\n${lines.join(',\n')}\n}`;
|
|
435
|
+
}
|
|
436
|
+
export function mark_done(relative_path) {
|
|
437
|
+
const source_file = _resolve_source(relative_path);
|
|
438
|
+
if (source_file === null || !_exists(source_file)) {
|
|
439
|
+
_print(`❌ Source file not found: ${relative_path}`);
|
|
440
|
+
process.exit(1);
|
|
441
|
+
}
|
|
442
|
+
apply_path_rewriter(relative_path);
|
|
443
|
+
const hashes = load_hashes();
|
|
444
|
+
hashes[relative_path] = effective_hash(relative_path);
|
|
445
|
+
save_hashes(hashes);
|
|
446
|
+
_print(`✅ Marked as condensed: ${relative_path}`);
|
|
447
|
+
}
|
|
448
|
+
export function apply_path_rewriter(relative_path) {
|
|
449
|
+
const target = path.join(MODULE_STATE.TARGET_DIR, relative_path);
|
|
450
|
+
if (!_exists(target) || !relative_path.endsWith('.md')) {
|
|
451
|
+
return false;
|
|
452
|
+
}
|
|
453
|
+
const original = _readText(target);
|
|
454
|
+
const rewritten = _rewrite_paths(original, relative_path);
|
|
455
|
+
if (rewritten === original) {
|
|
456
|
+
return false;
|
|
457
|
+
}
|
|
458
|
+
_writeText(target, rewritten);
|
|
459
|
+
return true;
|
|
460
|
+
}
|
|
461
|
+
export function mark_all_done() {
|
|
462
|
+
const hashes = load_hashes();
|
|
463
|
+
let count = 0;
|
|
464
|
+
for (const [source_file, relative] of _iter_sources()) {
|
|
465
|
+
if (!should_condense(source_file)) {
|
|
466
|
+
continue;
|
|
467
|
+
}
|
|
468
|
+
hashes[relative] = effective_hash(relative);
|
|
469
|
+
count += 1;
|
|
470
|
+
}
|
|
471
|
+
save_hashes(hashes);
|
|
472
|
+
_print(`✅ Marked ${count} files as condensed`);
|
|
473
|
+
}
|
|
474
|
+
export function list_changed_md(_source_dir) {
|
|
475
|
+
// _source_dir retained for signature compatibility but ignored (multi-root).
|
|
476
|
+
const hashes = load_hashes();
|
|
477
|
+
const changed = [];
|
|
478
|
+
for (const [source_file, relative] of _iter_sources()) {
|
|
479
|
+
if (!should_condense(source_file)) {
|
|
480
|
+
continue;
|
|
481
|
+
}
|
|
482
|
+
const current_hash = effective_hash(relative);
|
|
483
|
+
const stored_hash = hashes[relative];
|
|
484
|
+
if (stored_hash !== current_hash) {
|
|
485
|
+
changed.push(relative);
|
|
486
|
+
}
|
|
487
|
+
}
|
|
488
|
+
return changed;
|
|
489
|
+
}
|
|
490
|
+
export function find_stale_hashes(_source_dir) {
|
|
491
|
+
const hashes = load_hashes();
|
|
492
|
+
const stale = [];
|
|
493
|
+
for (const relative of Object.keys(hashes).sort((a, b) => (a < b ? -1 : a > b ? 1 : 0))) {
|
|
494
|
+
if (_resolve_source(relative) === null) {
|
|
495
|
+
stale.push(relative);
|
|
496
|
+
}
|
|
497
|
+
}
|
|
498
|
+
return stale;
|
|
499
|
+
}
|
|
500
|
+
export function clean_stale_hashes(_source_dir) {
|
|
501
|
+
const stale = find_stale_hashes(_source_dir);
|
|
502
|
+
if (stale.length === 0) {
|
|
503
|
+
return 0;
|
|
504
|
+
}
|
|
505
|
+
const hashes = load_hashes();
|
|
506
|
+
for (const relative of stale) {
|
|
507
|
+
delete hashes[relative];
|
|
508
|
+
}
|
|
509
|
+
save_hashes(hashes);
|
|
510
|
+
return stale.length;
|
|
511
|
+
}
|
|
512
|
+
export function should_condense(filepath) {
|
|
513
|
+
if (path.extname(filepath) !== '.md') {
|
|
514
|
+
return false;
|
|
515
|
+
}
|
|
516
|
+
if (COPY_AS_IS.has(path.basename(filepath))) {
|
|
517
|
+
return false;
|
|
518
|
+
}
|
|
519
|
+
// Determine logical relative parts so COPY_AS_IS_DIRS works for legacy +
|
|
520
|
+
// post-move source roots. Default to the full path parts (Python: Path.parts).
|
|
521
|
+
let rel_parts = filepath.split(path.sep).filter((s) => s.length > 0);
|
|
522
|
+
for (const root of MODULE_STATE.artefact_roots()) {
|
|
523
|
+
if (filepath !== root && !_isUnder(filepath, root)) {
|
|
524
|
+
continue;
|
|
525
|
+
}
|
|
526
|
+
rel_parts = _relativeToPosix(filepath, root).split('/');
|
|
527
|
+
break;
|
|
528
|
+
}
|
|
529
|
+
if (rel_parts.length > 0 && COPY_AS_IS_DIRS.has(rel_parts[0])) {
|
|
530
|
+
return false;
|
|
531
|
+
}
|
|
532
|
+
return true;
|
|
533
|
+
}
|
|
534
|
+
export function copy_file(source, target) {
|
|
535
|
+
_mkdirp(path.dirname(target));
|
|
536
|
+
fs.copyFileSync(source, target);
|
|
537
|
+
// shutil.copy2 also preserves metadata (mtime/mode); fidelity for content
|
|
538
|
+
// is what matters for the sync/hash contract.
|
|
539
|
+
try {
|
|
540
|
+
const st = fs.statSync(source);
|
|
541
|
+
fs.utimesSync(target, st.atime, st.mtime);
|
|
542
|
+
fs.chmodSync(target, st.mode);
|
|
543
|
+
}
|
|
544
|
+
catch {
|
|
545
|
+
/* best-effort metadata copy */
|
|
546
|
+
}
|
|
547
|
+
}
|
|
548
|
+
export function cleanup_stale(_source_dir, target_dir) {
|
|
549
|
+
let deleted = 0;
|
|
550
|
+
if (!_exists(target_dir)) {
|
|
551
|
+
return 0;
|
|
552
|
+
}
|
|
553
|
+
for (const target_file of _rglobSorted(target_dir, '*')) {
|
|
554
|
+
if (_isDir(target_file)) {
|
|
555
|
+
continue;
|
|
556
|
+
}
|
|
557
|
+
const relative = _relativeToPosix(target_file, target_dir);
|
|
558
|
+
if (_resolve_source(relative) === null) {
|
|
559
|
+
_print(` Deleting stale: ${relative}`);
|
|
560
|
+
fs.unlinkSync(target_file);
|
|
561
|
+
deleted += 1;
|
|
562
|
+
}
|
|
563
|
+
}
|
|
564
|
+
// Remove empty directories (reverse-sorted, deepest first).
|
|
565
|
+
const dirs = _rglobSorted(target_dir, '*')
|
|
566
|
+
.filter((p) => _isDir(p))
|
|
567
|
+
.sort((a, b) => (a < b ? 1 : a > b ? -1 : 0));
|
|
568
|
+
for (const dirpath of dirs) {
|
|
569
|
+
try {
|
|
570
|
+
if (fs.readdirSync(dirpath).length === 0) {
|
|
571
|
+
fs.rmdirSync(dirpath);
|
|
572
|
+
_print(` Removing empty dir: ${_relativeToPosix(dirpath, target_dir)}`);
|
|
573
|
+
}
|
|
574
|
+
}
|
|
575
|
+
catch {
|
|
576
|
+
/* races/permission — ignore, mirrors Python best-effort */
|
|
577
|
+
}
|
|
578
|
+
}
|
|
579
|
+
return deleted;
|
|
580
|
+
}
|
|
581
|
+
export function sync_non_md(_source_dir, target_dir) {
|
|
582
|
+
let copied = 0;
|
|
583
|
+
const seen = new Set();
|
|
584
|
+
for (const [source_file, relative] of _iter_sources()) {
|
|
585
|
+
if (should_condense(source_file)) {
|
|
586
|
+
continue; // .md files are condensed by the agent, not copied here
|
|
587
|
+
}
|
|
588
|
+
if (seen.has(relative)) {
|
|
589
|
+
continue;
|
|
590
|
+
}
|
|
591
|
+
seen.add(relative);
|
|
592
|
+
const target_file = path.join(target_dir, relative);
|
|
593
|
+
copy_file(source_file, target_file);
|
|
594
|
+
_print(` Copied: ${relative}`);
|
|
595
|
+
copied += 1;
|
|
596
|
+
}
|
|
597
|
+
return copied;
|
|
598
|
+
}
|
|
599
|
+
export function list_md_files(_source_dir) {
|
|
600
|
+
const files = [];
|
|
601
|
+
const seen = new Set();
|
|
602
|
+
for (const [source_file, relative] of _iter_sources()) {
|
|
603
|
+
if (!should_condense(source_file)) {
|
|
604
|
+
continue;
|
|
605
|
+
}
|
|
606
|
+
if (seen.has(relative)) {
|
|
607
|
+
continue;
|
|
608
|
+
}
|
|
609
|
+
seen.add(relative);
|
|
610
|
+
files.push(relative);
|
|
611
|
+
}
|
|
612
|
+
return files.sort((a, b) => (a < b ? -1 : a > b ? 1 : 0));
|
|
613
|
+
}
|
|
614
|
+
export function check_sync(_source_dir, target_dir) {
|
|
615
|
+
const missing = [];
|
|
616
|
+
const stale = [];
|
|
617
|
+
const seen = new Set();
|
|
618
|
+
for (const [, relative] of _iter_sources()) {
|
|
619
|
+
if (seen.has(relative)) {
|
|
620
|
+
continue;
|
|
621
|
+
}
|
|
622
|
+
seen.add(relative);
|
|
623
|
+
if (!_exists(path.join(target_dir, relative))) {
|
|
624
|
+
missing.push(relative);
|
|
625
|
+
}
|
|
626
|
+
}
|
|
627
|
+
if (_exists(target_dir)) {
|
|
628
|
+
for (const target_file of _rglobSorted(target_dir, '*')) {
|
|
629
|
+
if (_isDir(target_file)) {
|
|
630
|
+
continue;
|
|
631
|
+
}
|
|
632
|
+
const relative = _relativeToPosix(target_file, target_dir);
|
|
633
|
+
if (_resolve_source(relative) === null) {
|
|
634
|
+
stale.push(relative);
|
|
635
|
+
}
|
|
636
|
+
}
|
|
637
|
+
}
|
|
638
|
+
return [missing, stale];
|
|
639
|
+
}
|
|
640
|
+
// ── Multi-agent tool generation ──────────────────────────────────────
|
|
641
|
+
const TOOL_DIRS = {
|
|
642
|
+
'.claude/rules': '../../dist/agent-src/rules',
|
|
643
|
+
'.cursor/rules': '../../dist/agent-src/rules',
|
|
644
|
+
'.clinerules': '../dist/agent-src/rules',
|
|
645
|
+
};
|
|
646
|
+
const PERSONA_TOOL_DIRS = {
|
|
647
|
+
'.claude/personas': '../../dist/agent-src/personas',
|
|
648
|
+
'.cursor/personas': '../../dist/agent-src/personas',
|
|
649
|
+
};
|
|
650
|
+
const USER_TYPE_TOOL_DIRS = {
|
|
651
|
+
'.claude/user-types': '../../dist/agent-src/user-types',
|
|
652
|
+
'.cursor/user-types': '../../dist/agent-src/user-types',
|
|
653
|
+
};
|
|
654
|
+
const _DIR_TOOL_ID = {
|
|
655
|
+
'.claude/rules': 'claude-code',
|
|
656
|
+
'.cursor/rules': 'cursor',
|
|
657
|
+
'.clinerules': 'cline',
|
|
658
|
+
'.claude/personas': 'claude-code',
|
|
659
|
+
'.cursor/personas': 'cursor',
|
|
660
|
+
'.claude/user-types': 'claude-code',
|
|
661
|
+
'.cursor/user-types': 'cursor',
|
|
662
|
+
};
|
|
663
|
+
function _filter_tool_dirs(mapping) {
|
|
664
|
+
const out = {};
|
|
665
|
+
for (const [d, p] of Object.entries(mapping)) {
|
|
666
|
+
if (_tool_active(_DIR_TOOL_ID[d] ?? 'claude-code')) {
|
|
667
|
+
out[d] = p;
|
|
668
|
+
}
|
|
669
|
+
}
|
|
670
|
+
return out;
|
|
671
|
+
}
|
|
672
|
+
export function strip_frontmatter(content) {
|
|
673
|
+
if (content.startsWith('---')) {
|
|
674
|
+
const end = content.indexOf('---', 3);
|
|
675
|
+
if (end !== -1) {
|
|
676
|
+
content = _lstripNewlines(content.slice(end + 3));
|
|
677
|
+
}
|
|
678
|
+
}
|
|
679
|
+
return content;
|
|
680
|
+
}
|
|
681
|
+
// ── Path rewriter (P1 of road-to-path-fixes.md) ───────────────────────────
|
|
682
|
+
// Kept byte-identical to check_condensation.ts::_rewritePaths (the two MUST
|
|
683
|
+
// agree — see ADR-200 note). Mirrors condense.py::_rewrite_paths.
|
|
684
|
+
const _LEGACY_SRC_PREFIX = '.agent-src.uncondensed/';
|
|
685
|
+
const _PROJECTED_SRC_PREFIX = 'dist/agent-src/';
|
|
686
|
+
const _LEGACY_PROJECTED_SRC_PREFIX = '.agent-src/';
|
|
687
|
+
const _FM_LIST_ITEM_RE = /^(\s*-\s*)(["']?)([^"'\n]+?\.md)(["']?)\s*$/;
|
|
688
|
+
const _FM_PATH_PREFIX_RE = /^(\s*(?:-\s+)?path_prefix:\s*)(["']?)([^"'\n]+?)(["']?)\s*$/;
|
|
689
|
+
const _BODY_DOCS_RE = /\.\.\/\.\.\/(docs\/(?:guidelines|contracts)\/[^)\s]+\.md)/g;
|
|
690
|
+
const _FM_PLAIN_LIST_RE = /^\s*-\s*(["']?)([^"'\n]+?)\1\s*$/;
|
|
691
|
+
const _HRR_BANNER_MARKER = '<!-- agent-config:human-review-banner -->';
|
|
692
|
+
function _depth_prefix(source_relative_path) {
|
|
693
|
+
const parts = _posixParts(source_relative_path);
|
|
694
|
+
const depth = Math.max(parts.length - 1, 1);
|
|
695
|
+
return '../'.repeat(depth);
|
|
696
|
+
}
|
|
697
|
+
function _split_frontmatter(content) {
|
|
698
|
+
if (!content.startsWith('---\n')) {
|
|
699
|
+
return [null, content];
|
|
700
|
+
}
|
|
701
|
+
const end = content.indexOf('\n---\n', 4);
|
|
702
|
+
if (end === -1) {
|
|
703
|
+
return [null, content];
|
|
704
|
+
}
|
|
705
|
+
const fm_text = content.slice(4, end);
|
|
706
|
+
const body = content.slice(end + '\n---\n'.length);
|
|
707
|
+
return [fm_text.split('\n'), body];
|
|
708
|
+
}
|
|
709
|
+
function _rewrite_load_context_value(value, prefix) {
|
|
710
|
+
if (value.startsWith('../') || value.startsWith('./') || value.startsWith('/')) {
|
|
711
|
+
return value;
|
|
712
|
+
}
|
|
713
|
+
if (value.startsWith(_LEGACY_SRC_PREFIX)) {
|
|
714
|
+
return prefix + value.slice(_LEGACY_SRC_PREFIX.length);
|
|
715
|
+
}
|
|
716
|
+
if (value.startsWith(_PROJECTED_SRC_PREFIX)) {
|
|
717
|
+
return prefix + value.slice(_PROJECTED_SRC_PREFIX.length);
|
|
718
|
+
}
|
|
719
|
+
if (value.startsWith(_LEGACY_PROJECTED_SRC_PREFIX)) {
|
|
720
|
+
return prefix + value.slice(_LEGACY_PROJECTED_SRC_PREFIX.length);
|
|
721
|
+
}
|
|
722
|
+
return prefix + value;
|
|
723
|
+
}
|
|
724
|
+
function _rewrite_path_prefix_value(value) {
|
|
725
|
+
return value; // no-op — literal match pattern, not a file reference
|
|
726
|
+
}
|
|
727
|
+
function _rewrite_frontmatter_lines(lines, prefix) {
|
|
728
|
+
let in_load_context = false;
|
|
729
|
+
const out = [];
|
|
730
|
+
for (const line of lines) {
|
|
731
|
+
const bare = _lstrip(line);
|
|
732
|
+
if (bare.startsWith('load_context:') || bare.startsWith('load_context_eager:')) {
|
|
733
|
+
in_load_context = true;
|
|
734
|
+
out.push(line);
|
|
735
|
+
continue;
|
|
736
|
+
}
|
|
737
|
+
if (in_load_context) {
|
|
738
|
+
const m = _FM_LIST_ITEM_RE.exec(line);
|
|
739
|
+
if (m) {
|
|
740
|
+
const indent = m[1] ?? '';
|
|
741
|
+
const q1 = m[2] ?? '';
|
|
742
|
+
const value = m[3] ?? '';
|
|
743
|
+
const q2 = m[4] ?? '';
|
|
744
|
+
out.push(`${indent}${q1}${_rewrite_load_context_value(value, prefix)}${q2}`);
|
|
745
|
+
continue;
|
|
746
|
+
}
|
|
747
|
+
in_load_context = false;
|
|
748
|
+
}
|
|
749
|
+
const pm = _FM_PATH_PREFIX_RE.exec(line);
|
|
750
|
+
if (pm) {
|
|
751
|
+
const head = pm[1] ?? '';
|
|
752
|
+
const q1 = pm[2] ?? '';
|
|
753
|
+
const value = pm[3] ?? '';
|
|
754
|
+
const q2 = pm[4] ?? '';
|
|
755
|
+
out.push(`${head}${q1}${_rewrite_path_prefix_value(value)}${q2}`);
|
|
756
|
+
continue;
|
|
757
|
+
}
|
|
758
|
+
out.push(line);
|
|
759
|
+
}
|
|
760
|
+
return out;
|
|
761
|
+
}
|
|
762
|
+
function _rewrite_body_links(body, prefix) {
|
|
763
|
+
return body.replace(_BODY_DOCS_RE, (_m, tail) => prefix + tail);
|
|
764
|
+
}
|
|
765
|
+
function _parse_trust_and_owner(fm_lines) {
|
|
766
|
+
let level = 'core';
|
|
767
|
+
let hrr = false;
|
|
768
|
+
const packs = [];
|
|
769
|
+
const workspaces = [];
|
|
770
|
+
let in_trust = false;
|
|
771
|
+
let in_packs = false;
|
|
772
|
+
let in_workspaces = false;
|
|
773
|
+
for (const line of fm_lines) {
|
|
774
|
+
const stripped = _lstrip(line);
|
|
775
|
+
const indent = line.length - stripped.length;
|
|
776
|
+
if (indent === 0 && stripped.endsWith(':')) {
|
|
777
|
+
const key = stripped.slice(0, -1);
|
|
778
|
+
in_trust = key === 'trust';
|
|
779
|
+
in_packs = key === 'packs';
|
|
780
|
+
in_workspaces = key === 'workspaces';
|
|
781
|
+
continue;
|
|
782
|
+
}
|
|
783
|
+
if (in_trust && stripped.startsWith('level:')) {
|
|
784
|
+
const after = stripped.slice(stripped.indexOf(':') + 1);
|
|
785
|
+
level = _stripChars(_stripChars(_strip(after), '"'), "'");
|
|
786
|
+
}
|
|
787
|
+
else if (in_trust && stripped.startsWith('human_review_required:')) {
|
|
788
|
+
const after = stripped.slice(stripped.indexOf(':') + 1);
|
|
789
|
+
hrr = _strip(after).toLowerCase() === 'true';
|
|
790
|
+
}
|
|
791
|
+
else if (in_packs || in_workspaces) {
|
|
792
|
+
const m = _FM_PLAIN_LIST_RE.exec(line);
|
|
793
|
+
if (m) {
|
|
794
|
+
const value = _strip(m[2] ?? '');
|
|
795
|
+
(in_packs ? packs : workspaces).push(value);
|
|
796
|
+
}
|
|
797
|
+
}
|
|
798
|
+
}
|
|
799
|
+
let owner = 'unknown';
|
|
800
|
+
if (packs.length > 0) {
|
|
801
|
+
owner = packs[0].split('-')[0];
|
|
802
|
+
}
|
|
803
|
+
else if (workspaces.length > 0) {
|
|
804
|
+
owner = workspaces[0];
|
|
805
|
+
}
|
|
806
|
+
return [level, hrr, owner];
|
|
807
|
+
}
|
|
808
|
+
function _inject_hrr_banner(body, level, owner) {
|
|
809
|
+
if (body.includes(_HRR_BANNER_MARKER)) {
|
|
810
|
+
return body;
|
|
811
|
+
}
|
|
812
|
+
const banner = `${_HRR_BANNER_MARKER}\n` + `> HUMAN REVIEW REQUIRED · trust: ${level} · owner: ${owner}\n\n`;
|
|
813
|
+
return banner + _lstripNewlines(body);
|
|
814
|
+
}
|
|
815
|
+
export function _rewrite_paths(content, source_relative_path) {
|
|
816
|
+
const prefix = _depth_prefix(source_relative_path);
|
|
817
|
+
const [fm_lines, bodyInitial] = _split_frontmatter(content);
|
|
818
|
+
let body = _rewrite_body_links(bodyInitial, prefix);
|
|
819
|
+
if (fm_lines === null) {
|
|
820
|
+
return body;
|
|
821
|
+
}
|
|
822
|
+
const new_fm = _rewrite_frontmatter_lines(fm_lines, prefix);
|
|
823
|
+
const [level, hrr, owner] = _parse_trust_and_owner(fm_lines);
|
|
824
|
+
if (hrr && level) {
|
|
825
|
+
body = _inject_hrr_banner(body, level, owner);
|
|
826
|
+
}
|
|
827
|
+
return '---\n' + new_fm.join('\n') + '\n---\n' + body;
|
|
828
|
+
}
|
|
829
|
+
// Expose the HRR marker for tests (mirrors condense._HRR_BANNER_MARKER access).
|
|
830
|
+
export { _HRR_BANNER_MARKER };
|
|
831
|
+
// ── Consumer-scoped rule projection (road-to-request-scoped-rule-load P1) ──
|
|
832
|
+
//
|
|
833
|
+
// Opt-in via `projection.rule_workspaces: [<workspace-id>, …]` in
|
|
834
|
+
// `.agent-settings.yml`. Absent / empty = legacy-all (every rule projects —
|
|
835
|
+
// today's behaviour, non-breaking). When set, a non-kernel rule projects
|
|
836
|
+
// only if its `workspaces:` frontmatter intersects the configured set.
|
|
837
|
+
// Kernel rules (`type: always` / `alwaysApply: true`) ALWAYS project —
|
|
838
|
+
// the kernel is unconditional and workspace-independent by definition
|
|
839
|
+
// (rule-router contract § Schema v2). Untagged rules fail safe: they ship.
|
|
840
|
+
// ADR-040: projection-time filtering only, no runtime resolver.
|
|
841
|
+
function _read_projection_list(key) {
|
|
842
|
+
const data = load_agent_settings({ project_path: MODULE_STATE.SETTINGS_FILE });
|
|
843
|
+
const proj = data['projection'];
|
|
844
|
+
const value = typeof proj === 'object' && proj !== null && !Array.isArray(proj)
|
|
845
|
+
? proj[key]
|
|
846
|
+
: null;
|
|
847
|
+
if (Array.isArray(value) && value.length > 0) {
|
|
848
|
+
return value.map((v) => String(v));
|
|
849
|
+
}
|
|
850
|
+
return null;
|
|
851
|
+
}
|
|
852
|
+
function _read_rule_workspaces() {
|
|
853
|
+
return _read_projection_list('rule_workspaces');
|
|
854
|
+
}
|
|
855
|
+
function _read_rule_packs() {
|
|
856
|
+
return _read_projection_list('rule_packs');
|
|
857
|
+
}
|
|
858
|
+
/**
|
|
859
|
+
* Whether a rule source file projects under the given workspace + pack
|
|
860
|
+
* scopes. Both scopes are independent constraints: when configured, the
|
|
861
|
+
* rule's frontmatter list must intersect (installed workspaces AND
|
|
862
|
+
* installed packs). Kernel always projects; untagged axes fail safe.
|
|
863
|
+
*/
|
|
864
|
+
export function rule_in_scope(source_path, scope, pack_scope = null) {
|
|
865
|
+
if (scope === null && pack_scope === null) {
|
|
866
|
+
return true;
|
|
867
|
+
}
|
|
868
|
+
const [meta] = _parse_frontmatter(_readText(source_path));
|
|
869
|
+
if (meta['type'] === 'always' || meta['alwaysApply'] === true) {
|
|
870
|
+
return true; // kernel always projects
|
|
871
|
+
}
|
|
872
|
+
const axis = (key, configured) => {
|
|
873
|
+
if (configured === null) {
|
|
874
|
+
return true;
|
|
875
|
+
}
|
|
876
|
+
const values = Array.isArray(meta[key])
|
|
877
|
+
? meta[key].map((w) => String(w))
|
|
878
|
+
: [];
|
|
879
|
+
if (values.length === 0) {
|
|
880
|
+
return true; // untagged → fail safe: ship it
|
|
881
|
+
}
|
|
882
|
+
return values.some((v) => configured.includes(v));
|
|
883
|
+
};
|
|
884
|
+
return axis('workspaces', scope) && axis('packs', pack_scope);
|
|
885
|
+
}
|
|
886
|
+
/** List rule basenames under RULES_SOURCE, workspace/pack scope applied. */
|
|
887
|
+
function _scoped_rule_basenames() {
|
|
888
|
+
const scope = _read_rule_workspaces();
|
|
889
|
+
const pack_scope = _read_rule_packs();
|
|
890
|
+
return _iterdirSorted(MODULE_STATE.RULES_SOURCE)
|
|
891
|
+
.filter((p) => p.endsWith('.md') && _isFile(p))
|
|
892
|
+
.filter((p) => rule_in_scope(p, scope, pack_scope))
|
|
893
|
+
.map((p) => path.basename(p))
|
|
894
|
+
.sort((a, b) => (a < b ? -1 : a > b ? 1 : 0));
|
|
895
|
+
}
|
|
896
|
+
export function generate_rule_symlinks() {
|
|
897
|
+
const rules = _scoped_rule_basenames();
|
|
898
|
+
const tool_dirs = _filter_tool_dirs(TOOL_DIRS);
|
|
899
|
+
let thin_files = null;
|
|
900
|
+
if (_lean_projection_mode() === 'thin') {
|
|
901
|
+
// The `project_thin_rules` twin is not ported (out of scope — thin mode
|
|
902
|
+
// is opt-in and not exercised by golden parity). Throw a clear error if
|
|
903
|
+
// a consumer actually enables it, mirroring an unmet import.
|
|
904
|
+
throw new Error('lean_projection.mode=thin requires project_thin_rules (not ported in condense.ts)');
|
|
905
|
+
}
|
|
906
|
+
let total = 0;
|
|
907
|
+
for (const [tool_dir, rel_prefix] of Object.entries(tool_dirs)) {
|
|
908
|
+
const target_dir = path.join(MODULE_STATE.PROJECT_ROOT, tool_dir);
|
|
909
|
+
_mkdirp(target_dir);
|
|
910
|
+
// Clean stale symlinks
|
|
911
|
+
for (const item of _iterdirSorted(target_dir)) {
|
|
912
|
+
const name = path.basename(item);
|
|
913
|
+
if (_isSymlink(item) && !rules.includes(name) && name !== 'README.md') {
|
|
914
|
+
fs.unlinkSync(item);
|
|
915
|
+
}
|
|
916
|
+
}
|
|
917
|
+
for (const rule of rules) {
|
|
918
|
+
const link = path.join(target_dir, rule);
|
|
919
|
+
if (_existsOrSymlink(link)) {
|
|
920
|
+
fs.unlinkSync(link);
|
|
921
|
+
}
|
|
922
|
+
if (thin_files !== null) {
|
|
923
|
+
_writeText(link, thin_files[rule]);
|
|
924
|
+
}
|
|
925
|
+
else {
|
|
926
|
+
fs.symlinkSync(path.join(rel_prefix, rule), link);
|
|
927
|
+
}
|
|
928
|
+
total += 1;
|
|
929
|
+
}
|
|
930
|
+
}
|
|
931
|
+
const source_count = rules.length;
|
|
932
|
+
for (const tool_dir of Object.keys(tool_dirs)) {
|
|
933
|
+
const target_dir = path.join(MODULE_STATE.PROJECT_ROOT, tool_dir);
|
|
934
|
+
const tool_count = _iterdirSorted(target_dir).filter((f) => f.endsWith('.md')).length;
|
|
935
|
+
if (tool_count !== source_count) {
|
|
936
|
+
_print(` ⚠️ ${tool_dir}: ${tool_count} rules (expected ${source_count})`);
|
|
937
|
+
}
|
|
938
|
+
}
|
|
939
|
+
info(` ✅ Created ${total} rule symlinks across ${Object.keys(tool_dirs).length} tool directories (${source_count} rules each)`);
|
|
940
|
+
return total;
|
|
941
|
+
}
|
|
942
|
+
export function generate_windsurfrules() {
|
|
943
|
+
const rules = _scoped_rule_basenames();
|
|
944
|
+
const parts = ['# Auto-generated from dist/agent-src/rules/ — do not edit directly\n'];
|
|
945
|
+
for (const rule of rules) {
|
|
946
|
+
const p = path.join(MODULE_STATE.RULES_SOURCE, rule);
|
|
947
|
+
const content = strip_frontmatter(_readText(p));
|
|
948
|
+
parts.push(`---\n\n${_strip(content)}\n`);
|
|
949
|
+
}
|
|
950
|
+
const output = path.join(MODULE_STATE.PROJECT_ROOT, '.windsurfrules');
|
|
951
|
+
_writeText(output, parts.join('\n') + '\n');
|
|
952
|
+
info(` ✅ Generated .windsurfrules (${rules.length} rules)`);
|
|
953
|
+
return rules.length;
|
|
954
|
+
}
|
|
955
|
+
// ── Modern editor formats ────────────────────────────────────────────
|
|
956
|
+
function _CURSOR_RULES_MDC_DIR() {
|
|
957
|
+
return path.join(MODULE_STATE.PROJECT_ROOT, '.cursor', 'rules');
|
|
958
|
+
}
|
|
959
|
+
function _WINDSURF_RULES_DIR() {
|
|
960
|
+
return path.join(MODULE_STATE.PROJECT_ROOT, '.windsurf', 'rules');
|
|
961
|
+
}
|
|
962
|
+
function _WINDSURF_WORKFLOWS_DIR() {
|
|
963
|
+
return path.join(MODULE_STATE.PROJECT_ROOT, '.windsurf', 'workflows');
|
|
964
|
+
}
|
|
965
|
+
function _CURSOR_COMMANDS_DIR() {
|
|
966
|
+
return path.join(MODULE_STATE.PROJECT_ROOT, '.cursor', 'commands');
|
|
967
|
+
}
|
|
968
|
+
function _parse_frontmatter(content) {
|
|
969
|
+
if (!content.startsWith('---')) {
|
|
970
|
+
return [{}, content];
|
|
971
|
+
}
|
|
972
|
+
const end = content.indexOf('\n---', 3);
|
|
973
|
+
if (end === -1) {
|
|
974
|
+
return [{}, content];
|
|
975
|
+
}
|
|
976
|
+
const raw = _strip(content.slice(3, end));
|
|
977
|
+
const body = _lstripNewlines(content.slice(end + 4));
|
|
978
|
+
// Python: `meta = yaml.safe_load(raw) or {}` inside try/except YAMLError.
|
|
979
|
+
let meta = _yamlParse(raw);
|
|
980
|
+
if (meta === null || meta === undefined) {
|
|
981
|
+
meta = {};
|
|
982
|
+
}
|
|
983
|
+
if (typeof meta === 'object' && meta !== null && !Array.isArray(meta)) {
|
|
984
|
+
return [meta, body];
|
|
985
|
+
}
|
|
986
|
+
return [{}, body];
|
|
987
|
+
}
|
|
988
|
+
function _yaml_scalar(value) {
|
|
989
|
+
return JSON.stringify(value);
|
|
990
|
+
}
|
|
991
|
+
/**
|
|
992
|
+
* Derive host-native activation globs from a rule's `triggers:` frontmatter
|
|
993
|
+
* (road-to-request-scoped-rule-load Phase 2). `file_pattern` triggers map
|
|
994
|
+
* verbatim; `path_prefix` triggers map to `<prefix>**`. Keyword / phrase /
|
|
995
|
+
* intent / command triggers produce no glob — those rules stay
|
|
996
|
+
* description-activated (Cursor Agent-Requested / Windsurf model_decision).
|
|
997
|
+
*/
|
|
998
|
+
export function derive_trigger_globs(meta) {
|
|
999
|
+
const triggers = meta['triggers'];
|
|
1000
|
+
if (!Array.isArray(triggers)) {
|
|
1001
|
+
return [];
|
|
1002
|
+
}
|
|
1003
|
+
const globs = [];
|
|
1004
|
+
for (const t of triggers) {
|
|
1005
|
+
if (t === null || typeof t !== 'object' || Array.isArray(t))
|
|
1006
|
+
continue;
|
|
1007
|
+
const obj = t;
|
|
1008
|
+
if (typeof obj['file_pattern'] === 'string' && obj['file_pattern']) {
|
|
1009
|
+
globs.push(obj['file_pattern']);
|
|
1010
|
+
}
|
|
1011
|
+
else if (typeof obj['path_prefix'] === 'string' && obj['path_prefix']) {
|
|
1012
|
+
const prefix = obj['path_prefix'];
|
|
1013
|
+
globs.push(prefix.endsWith('/') ? `${prefix}**` : `${prefix}**`);
|
|
1014
|
+
}
|
|
1015
|
+
}
|
|
1016
|
+
// De-dup, keep declaration order (deterministic output).
|
|
1017
|
+
return [...new Set(globs)];
|
|
1018
|
+
}
|
|
1019
|
+
export function _emit_cursor_mdc(source, target) {
|
|
1020
|
+
const [meta, body] = _parse_frontmatter(_readText(source));
|
|
1021
|
+
const description = _strip(String(meta['description'] ?? '').replace(/\n/g, ' '));
|
|
1022
|
+
const always_apply = Boolean(meta['alwaysApply'] || meta['type'] === 'always');
|
|
1023
|
+
// Path-shaped triggers become Cursor auto-attach globs; rules without
|
|
1024
|
+
// them keep `globs: ` empty and stay Agent-Requested via description.
|
|
1025
|
+
const globs = always_apply ? [] : derive_trigger_globs(meta);
|
|
1026
|
+
const lines = [
|
|
1027
|
+
'---',
|
|
1028
|
+
`description: ${_yaml_scalar(description)}`,
|
|
1029
|
+
`globs: ${globs.join(',')}`,
|
|
1030
|
+
`alwaysApply: ${always_apply ? 'true' : 'false'}`,
|
|
1031
|
+
'---',
|
|
1032
|
+
'',
|
|
1033
|
+
_pyRstrip(body) + '\n',
|
|
1034
|
+
];
|
|
1035
|
+
_mkdirp(path.dirname(target));
|
|
1036
|
+
_writeText(target, lines.join('\n'));
|
|
1037
|
+
}
|
|
1038
|
+
export function _emit_windsurf_rule(source, target) {
|
|
1039
|
+
const [meta, body] = _parse_frontmatter(_readText(source));
|
|
1040
|
+
const description = _strip(String(meta['description'] ?? '').replace(/\n/g, ' '));
|
|
1041
|
+
const always_apply = Boolean(meta['alwaysApply'] || meta['type'] === 'always');
|
|
1042
|
+
// Path-shaped triggers activate host-natively via Windsurf's `glob`
|
|
1043
|
+
// trigger; keyword/intent-only rules keep `model_decision`.
|
|
1044
|
+
const globs = always_apply ? [] : derive_trigger_globs(meta);
|
|
1045
|
+
const trigger = always_apply ? 'always_on' : globs.length > 0 ? 'glob' : 'model_decision';
|
|
1046
|
+
const lines = [
|
|
1047
|
+
'---',
|
|
1048
|
+
`trigger: ${trigger}`,
|
|
1049
|
+
`description: ${_yaml_scalar(description)}`,
|
|
1050
|
+
`globs: ${globs.join(',')}`,
|
|
1051
|
+
'---',
|
|
1052
|
+
'',
|
|
1053
|
+
_pyRstrip(body) + '\n',
|
|
1054
|
+
];
|
|
1055
|
+
_mkdirp(path.dirname(target));
|
|
1056
|
+
_writeText(target, lines.join('\n'));
|
|
1057
|
+
}
|
|
1058
|
+
/** Python str.rstrip() with no args. */
|
|
1059
|
+
function _pyRstrip(s) {
|
|
1060
|
+
return s.replace(/\s+$/u, '');
|
|
1061
|
+
}
|
|
1062
|
+
function _clean_modern_dir(target_dir, valid_names) {
|
|
1063
|
+
if (!_exists(target_dir)) {
|
|
1064
|
+
return;
|
|
1065
|
+
}
|
|
1066
|
+
for (const item of _iterdirSorted(target_dir)) {
|
|
1067
|
+
const name = path.basename(item);
|
|
1068
|
+
if (name === 'README.md') {
|
|
1069
|
+
continue;
|
|
1070
|
+
}
|
|
1071
|
+
if (!valid_names.has(name)) {
|
|
1072
|
+
if (_isDir(item) && !_isSymlink(item)) {
|
|
1073
|
+
fs.rmSync(item, { recursive: true, force: true });
|
|
1074
|
+
}
|
|
1075
|
+
else {
|
|
1076
|
+
fs.unlinkSync(item);
|
|
1077
|
+
}
|
|
1078
|
+
}
|
|
1079
|
+
}
|
|
1080
|
+
}
|
|
1081
|
+
export function generate_cursor_mdc_rules() {
|
|
1082
|
+
const scope = _read_rule_workspaces();
|
|
1083
|
+
const pack_scope = _read_rule_packs();
|
|
1084
|
+
const rules = _rglobSorted(MODULE_STATE.RULES_SOURCE, '*.md')
|
|
1085
|
+
.filter((p) => _isFile(p))
|
|
1086
|
+
.filter((p) => rule_in_scope(p, scope, pack_scope));
|
|
1087
|
+
const stems = rules.map((r) => path.basename(r, '.md'));
|
|
1088
|
+
const valid = new Set([
|
|
1089
|
+
...stems.map((s) => `${s}.mdc`),
|
|
1090
|
+
...rules.map((r) => path.basename(r)),
|
|
1091
|
+
]);
|
|
1092
|
+
_clean_modern_dir(_CURSOR_RULES_MDC_DIR(), valid);
|
|
1093
|
+
for (const rule of rules) {
|
|
1094
|
+
_emit_cursor_mdc(rule, path.join(_CURSOR_RULES_MDC_DIR(), `${path.basename(rule, '.md')}.mdc`));
|
|
1095
|
+
}
|
|
1096
|
+
info(` ✅ Wrote ${rules.length} \`.cursor/rules/*.mdc\` files`);
|
|
1097
|
+
return rules.length;
|
|
1098
|
+
}
|
|
1099
|
+
export function generate_windsurf_modern_rules() {
|
|
1100
|
+
const scope = _read_rule_workspaces();
|
|
1101
|
+
const pack_scope = _read_rule_packs();
|
|
1102
|
+
const rules = _rglobSorted(MODULE_STATE.RULES_SOURCE, '*.md')
|
|
1103
|
+
.filter((p) => _isFile(p))
|
|
1104
|
+
.filter((p) => rule_in_scope(p, scope, pack_scope));
|
|
1105
|
+
const valid = new Set(rules.map((r) => path.basename(r)));
|
|
1106
|
+
_clean_modern_dir(_WINDSURF_RULES_DIR(), valid);
|
|
1107
|
+
for (const rule of rules) {
|
|
1108
|
+
_emit_windsurf_rule(rule, path.join(_WINDSURF_RULES_DIR(), path.basename(rule)));
|
|
1109
|
+
}
|
|
1110
|
+
info(` ✅ Wrote ${rules.length} \`.windsurf/rules/*.md\` files`);
|
|
1111
|
+
return rules.length;
|
|
1112
|
+
}
|
|
1113
|
+
export function generate_cursor_commands(active_command_slugs = null) {
|
|
1114
|
+
if (!_isDir(path.join(MODULE_STATE.PROJECT_ROOT, 'src', 'domains'))) {
|
|
1115
|
+
return 0;
|
|
1116
|
+
}
|
|
1117
|
+
const cmds = [...iterCommands()].filter(([, slug]) => active_command_slugs === null || active_command_slugs.has(slug));
|
|
1118
|
+
const valid = new Set(cmds.map(([, slug]) => `${slug}.md`));
|
|
1119
|
+
_clean_modern_dir(_CURSOR_COMMANDS_DIR(), valid);
|
|
1120
|
+
_mkdirp(_CURSOR_COMMANDS_DIR());
|
|
1121
|
+
let count = 0;
|
|
1122
|
+
for (const [source_file, slug] of cmds) {
|
|
1123
|
+
const link = path.join(_CURSOR_COMMANDS_DIR(), `${slug}.md`);
|
|
1124
|
+
if (_existsOrSymlink(link)) {
|
|
1125
|
+
fs.unlinkSync(link);
|
|
1126
|
+
}
|
|
1127
|
+
const rel = path.join('../..', _relativeToPosix(source_file, MODULE_STATE.PROJECT_ROOT));
|
|
1128
|
+
fs.symlinkSync(rel, link);
|
|
1129
|
+
count += 1;
|
|
1130
|
+
}
|
|
1131
|
+
info(` ✅ Linked ${count} \`.cursor/commands/*.md\` files`);
|
|
1132
|
+
return count;
|
|
1133
|
+
}
|
|
1134
|
+
export function generate_windsurf_workflows(active_command_slugs = null) {
|
|
1135
|
+
if (!_isDir(path.join(MODULE_STATE.PROJECT_ROOT, 'src', 'domains'))) {
|
|
1136
|
+
return 0;
|
|
1137
|
+
}
|
|
1138
|
+
const cmds = [...iterCommands()].filter(([, slug]) => active_command_slugs === null || active_command_slugs.has(slug));
|
|
1139
|
+
const valid = new Set(cmds.map(([, slug]) => `${slug}.md`));
|
|
1140
|
+
_clean_modern_dir(_WINDSURF_WORKFLOWS_DIR(), valid);
|
|
1141
|
+
_mkdirp(_WINDSURF_WORKFLOWS_DIR());
|
|
1142
|
+
let count = 0;
|
|
1143
|
+
for (const [source_file, slug] of cmds) {
|
|
1144
|
+
const link = path.join(_WINDSURF_WORKFLOWS_DIR(), `${slug}.md`);
|
|
1145
|
+
if (_existsOrSymlink(link)) {
|
|
1146
|
+
fs.unlinkSync(link);
|
|
1147
|
+
}
|
|
1148
|
+
const rel = path.join('../..', _relativeToPosix(source_file, MODULE_STATE.PROJECT_ROOT));
|
|
1149
|
+
fs.symlinkSync(rel, link);
|
|
1150
|
+
count += 1;
|
|
1151
|
+
}
|
|
1152
|
+
info(` ✅ Linked ${count} \`.windsurf/workflows/*.md\` files`);
|
|
1153
|
+
return count;
|
|
1154
|
+
}
|
|
1155
|
+
export function generate_gemini_md() {
|
|
1156
|
+
const link = path.join(MODULE_STATE.PROJECT_ROOT, 'GEMINI.md');
|
|
1157
|
+
if (_existsOrSymlink(link)) {
|
|
1158
|
+
fs.unlinkSync(link);
|
|
1159
|
+
}
|
|
1160
|
+
fs.symlinkSync('AGENTS.md', link);
|
|
1161
|
+
info(' ✅ Created GEMINI.md → AGENTS.md symlink');
|
|
1162
|
+
}
|
|
1163
|
+
function _command_slug(source_file) {
|
|
1164
|
+
const rel = _relativeToPosix(source_file, MODULE_STATE.COMMANDS_SOURCE);
|
|
1165
|
+
return _posixParts(rel.replace(/\.md$/, '')).join('-');
|
|
1166
|
+
}
|
|
1167
|
+
void _command_slug; // mirrors the Python helper; not on the hot path here
|
|
1168
|
+
/**
|
|
1169
|
+
* Yield [source_file, slug] for every command, sourced from src/domains/.
|
|
1170
|
+
* Mirrors condense._iter_commands (ADR-044 amendment).
|
|
1171
|
+
*/
|
|
1172
|
+
function* iterCommands() {
|
|
1173
|
+
const src_domains = path.join(MODULE_STATE.PROJECT_ROOT, 'src', 'domains');
|
|
1174
|
+
if (!_isDir(src_domains)) {
|
|
1175
|
+
return;
|
|
1176
|
+
}
|
|
1177
|
+
for (const source_file of _rglobSorted(src_domains, 'command.md')) {
|
|
1178
|
+
if (!_isFile(source_file)) {
|
|
1179
|
+
continue;
|
|
1180
|
+
}
|
|
1181
|
+
const rel = _relativeToPosix(source_file, MODULE_STATE.PROJECT_ROOT);
|
|
1182
|
+
let slug = _command_path_to_slug(rel);
|
|
1183
|
+
if (!slug) {
|
|
1184
|
+
continue;
|
|
1185
|
+
}
|
|
1186
|
+
const pack_id = _relativeToPosix(source_file, src_domains).split('/')[0];
|
|
1187
|
+
const prefix = _domains_slug_prefix(pack_id);
|
|
1188
|
+
if (prefix && slug !== prefix && !slug.startsWith(prefix + '-')) {
|
|
1189
|
+
slug = `${prefix}-${slug}`;
|
|
1190
|
+
}
|
|
1191
|
+
yield [source_file, slug];
|
|
1192
|
+
}
|
|
1193
|
+
}
|
|
1194
|
+
function _read_model_auto_switch() {
|
|
1195
|
+
const data = load_agent_settings({ project_path: MODULE_STATE.SETTINGS_FILE });
|
|
1196
|
+
const model = data['model'];
|
|
1197
|
+
const value = typeof model === 'object' && model !== null && !Array.isArray(model)
|
|
1198
|
+
? model['auto_switch']
|
|
1199
|
+
: null;
|
|
1200
|
+
if (typeof value === 'string' && ['auto', 'suggest', 'off'].includes(value.trim().toLowerCase())) {
|
|
1201
|
+
return value.trim().toLowerCase();
|
|
1202
|
+
}
|
|
1203
|
+
return 'suggest';
|
|
1204
|
+
}
|
|
1205
|
+
function _read_projection_mode() {
|
|
1206
|
+
const data = load_agent_settings({ project_path: MODULE_STATE.SETTINGS_FILE });
|
|
1207
|
+
const proj = data['projection'];
|
|
1208
|
+
const value = typeof proj === 'object' && proj !== null && !Array.isArray(proj)
|
|
1209
|
+
? proj['mode']
|
|
1210
|
+
: null;
|
|
1211
|
+
if (typeof value === 'string' && ['legacy-all', 'scoped'].includes(value.trim().toLowerCase())) {
|
|
1212
|
+
return value.trim().toLowerCase();
|
|
1213
|
+
}
|
|
1214
|
+
return 'legacy-all';
|
|
1215
|
+
}
|
|
1216
|
+
function _domains_slug_prefix(pack_id) {
|
|
1217
|
+
const manifest = path.join(MODULE_STATE.PROJECT_ROOT, 'src', 'domains', pack_id, 'pack.yaml');
|
|
1218
|
+
if (!_isFile(manifest)) {
|
|
1219
|
+
return '';
|
|
1220
|
+
}
|
|
1221
|
+
const m = _SLUG_PREFIX_RE.exec(_readText(manifest));
|
|
1222
|
+
return m ? m[1] : '';
|
|
1223
|
+
}
|
|
1224
|
+
function _command_path_to_slug(manifest_path) {
|
|
1225
|
+
const logical = strip_source_prefix(manifest_path);
|
|
1226
|
+
if (logical && logical.startsWith('commands/')) {
|
|
1227
|
+
return _posixParts(logical.slice('commands/'.length).replace(/\.md$/, '')).join('-');
|
|
1228
|
+
}
|
|
1229
|
+
const parts = manifest_path.split(path.sep).filter((s) => s.length > 0);
|
|
1230
|
+
const i = parts.indexOf('commands');
|
|
1231
|
+
return parts
|
|
1232
|
+
.slice(i + 1)
|
|
1233
|
+
.join('/')
|
|
1234
|
+
.replace(/\.md$/, '')
|
|
1235
|
+
.split('/')
|
|
1236
|
+
.join('-');
|
|
1237
|
+
}
|
|
1238
|
+
function _skill_path_to_name(manifest_path) {
|
|
1239
|
+
const parts = manifest_path.split(path.sep).filter((s) => s.length > 0);
|
|
1240
|
+
const i = parts.indexOf('skills');
|
|
1241
|
+
return parts[i + 1];
|
|
1242
|
+
}
|
|
1243
|
+
void _skill_path_to_name;
|
|
1244
|
+
function _resolve_active_predicates() {
|
|
1245
|
+
if (_read_projection_mode() !== 'scoped') {
|
|
1246
|
+
return [null, null];
|
|
1247
|
+
}
|
|
1248
|
+
// The `config` package twins (packs / session_profiles / profiles) are not
|
|
1249
|
+
// ported (out of scope — scoped mode is opt-in and not exercised by golden
|
|
1250
|
+
// parity). Throw a clear error if a consumer enables it, mirroring an
|
|
1251
|
+
// unmet import.
|
|
1252
|
+
throw new Error('projection.mode=scoped requires the config package (not ported in condense.ts)');
|
|
1253
|
+
}
|
|
1254
|
+
function _model_tier(skill_md) {
|
|
1255
|
+
if (!_exists(skill_md)) {
|
|
1256
|
+
return null;
|
|
1257
|
+
}
|
|
1258
|
+
const text = fs.readFileSync(skill_md).toString('utf-8');
|
|
1259
|
+
if (!text.startsWith('---\n')) {
|
|
1260
|
+
return null;
|
|
1261
|
+
}
|
|
1262
|
+
const end = text.indexOf('\n---\n', 4);
|
|
1263
|
+
if (end === -1) {
|
|
1264
|
+
return null;
|
|
1265
|
+
}
|
|
1266
|
+
const m = _MODEL_TIER_RE.exec(text.slice(4, end));
|
|
1267
|
+
return m ? m[1] : null;
|
|
1268
|
+
}
|
|
1269
|
+
function _render_native_model_md(src_md, tier) {
|
|
1270
|
+
const text = _readText(src_md);
|
|
1271
|
+
const model = _TIER_TO_CLAUDE_MODEL[tier];
|
|
1272
|
+
return text.replace(_MODEL_TIER_RE, `model: ${model}`);
|
|
1273
|
+
}
|
|
1274
|
+
export function generate_claude_skills(active_skill_names = null) {
|
|
1275
|
+
if (!_exists(MODULE_STATE.SKILLS_SOURCE)) {
|
|
1276
|
+
process.stderr.write(' ⚠️ dist/agent-src/skills/ not found — skipping skills\n');
|
|
1277
|
+
return 0;
|
|
1278
|
+
}
|
|
1279
|
+
let skills = _iterdirSorted(MODULE_STATE.SKILLS_SOURCE)
|
|
1280
|
+
.filter((p) => _isDir(p))
|
|
1281
|
+
.map((p) => path.basename(p))
|
|
1282
|
+
.sort((a, b) => (a < b ? -1 : a > b ? 1 : 0));
|
|
1283
|
+
if (active_skill_names !== null) {
|
|
1284
|
+
skills = skills.filter((s) => active_skill_names.has(s));
|
|
1285
|
+
}
|
|
1286
|
+
const skill_set = new Set(skills);
|
|
1287
|
+
const command_slugs = new Set([...iterCommands()].map(([, slug]) => slug));
|
|
1288
|
+
_mkdirp(MODULE_STATE.CLAUDE_SKILLS_DIR);
|
|
1289
|
+
const auto = _read_model_auto_switch() === 'auto';
|
|
1290
|
+
for (const item of _iterdirSorted(MODULE_STATE.CLAUDE_SKILLS_DIR)) {
|
|
1291
|
+
const name = path.basename(item);
|
|
1292
|
+
if (skill_set.has(name) || command_slugs.has(name) || name === 'README.md') {
|
|
1293
|
+
continue;
|
|
1294
|
+
}
|
|
1295
|
+
if (_isSymlink(item)) {
|
|
1296
|
+
fs.unlinkSync(item);
|
|
1297
|
+
}
|
|
1298
|
+
else if (_isDirNoFollow(item)) {
|
|
1299
|
+
const skill_md = path.join(item, 'SKILL.md');
|
|
1300
|
+
if (_isFile(skill_md) && !_isSymlink(skill_md)) {
|
|
1301
|
+
fs.rmSync(item, { recursive: true, force: true });
|
|
1302
|
+
}
|
|
1303
|
+
}
|
|
1304
|
+
}
|
|
1305
|
+
let count = 0;
|
|
1306
|
+
let rendered = 0;
|
|
1307
|
+
for (const skill of skills) {
|
|
1308
|
+
const link = path.join(MODULE_STATE.CLAUDE_SKILLS_DIR, skill);
|
|
1309
|
+
const src_dir = path.join(MODULE_STATE.SKILLS_SOURCE, skill);
|
|
1310
|
+
const value = auto ? _model_tier(path.join(src_dir, 'SKILL.md')) : null;
|
|
1311
|
+
if (_isSymlink(link)) {
|
|
1312
|
+
fs.unlinkSync(link);
|
|
1313
|
+
}
|
|
1314
|
+
else if (_isDirNoFollow(link)) {
|
|
1315
|
+
fs.rmSync(link, { recursive: true, force: true });
|
|
1316
|
+
}
|
|
1317
|
+
else if (_existsOrSymlink(link)) {
|
|
1318
|
+
fs.unlinkSync(link);
|
|
1319
|
+
}
|
|
1320
|
+
if (value !== null && value in _TIER_TO_CLAUDE_MODEL) {
|
|
1321
|
+
_mkdirp(link);
|
|
1322
|
+
for (const entry of _iterdirSorted(src_dir)) {
|
|
1323
|
+
const entryName = path.basename(entry);
|
|
1324
|
+
if (entryName === 'SKILL.md') {
|
|
1325
|
+
_writeText(path.join(link, 'SKILL.md'), _render_native_model_md(entry, value));
|
|
1326
|
+
}
|
|
1327
|
+
else {
|
|
1328
|
+
fs.symlinkSync(path.join('../../../dist/agent-src/skills', skill, entryName), path.join(link, entryName));
|
|
1329
|
+
}
|
|
1330
|
+
}
|
|
1331
|
+
rendered += 1;
|
|
1332
|
+
}
|
|
1333
|
+
else {
|
|
1334
|
+
fs.symlinkSync(path.join('../../dist/agent-src/skills', skill), link);
|
|
1335
|
+
}
|
|
1336
|
+
count += 1;
|
|
1337
|
+
}
|
|
1338
|
+
const suffix = rendered ? ` (${rendered} rendered with native model:)` : '';
|
|
1339
|
+
info(` ✅ Created ${count} skill entries in .claude/skills/${suffix}`);
|
|
1340
|
+
return count;
|
|
1341
|
+
}
|
|
1342
|
+
export function extract_description_from_md(content) {
|
|
1343
|
+
for (const raw of _strip(content).split('\n')) {
|
|
1344
|
+
const line = _strip(raw);
|
|
1345
|
+
if (line.startsWith('# ')) {
|
|
1346
|
+
return _strip(line.slice(2));
|
|
1347
|
+
}
|
|
1348
|
+
if (line && !line.startsWith('#')) {
|
|
1349
|
+
return line.slice(0, 120);
|
|
1350
|
+
}
|
|
1351
|
+
}
|
|
1352
|
+
return '';
|
|
1353
|
+
}
|
|
1354
|
+
export function generate_claude_commands(active_command_slugs = null) {
|
|
1355
|
+
if (!_isDir(path.join(MODULE_STATE.PROJECT_ROOT, 'src', 'domains'))) {
|
|
1356
|
+
process.stderr.write(' ⚠️ src/domains/ not found — skipping commands\n');
|
|
1357
|
+
return 0;
|
|
1358
|
+
}
|
|
1359
|
+
_mkdirp(MODULE_STATE.CLAUDE_SKILLS_DIR);
|
|
1360
|
+
let skill_names = new Set();
|
|
1361
|
+
if (_exists(MODULE_STATE.SKILLS_SOURCE)) {
|
|
1362
|
+
skill_names = new Set(_iterdirSorted(MODULE_STATE.SKILLS_SOURCE)
|
|
1363
|
+
.filter((p) => _isDir(p))
|
|
1364
|
+
.map((p) => path.basename(p)));
|
|
1365
|
+
}
|
|
1366
|
+
const current_slugs = new Set();
|
|
1367
|
+
let count = 0;
|
|
1368
|
+
let skipped = 0;
|
|
1369
|
+
let rendered = 0;
|
|
1370
|
+
const auto = _read_model_auto_switch() === 'auto';
|
|
1371
|
+
for (const [source_file, slug] of iterCommands()) {
|
|
1372
|
+
if (active_command_slugs !== null && !active_command_slugs.has(slug)) {
|
|
1373
|
+
continue;
|
|
1374
|
+
}
|
|
1375
|
+
if (skill_names.has(slug)) {
|
|
1376
|
+
skipped += 1;
|
|
1377
|
+
continue;
|
|
1378
|
+
}
|
|
1379
|
+
current_slugs.add(slug);
|
|
1380
|
+
const skill_dir = path.join(MODULE_STATE.CLAUDE_SKILLS_DIR, slug);
|
|
1381
|
+
_mkdirp(skill_dir);
|
|
1382
|
+
const skill_file = path.join(skill_dir, 'SKILL.md');
|
|
1383
|
+
if (_existsOrSymlink(skill_file)) {
|
|
1384
|
+
fs.unlinkSync(skill_file);
|
|
1385
|
+
}
|
|
1386
|
+
const rel_path = _relativeToPosix(source_file, MODULE_STATE.PROJECT_ROOT);
|
|
1387
|
+
const value = auto ? _model_tier(source_file) : null;
|
|
1388
|
+
if (value !== null && value in _TIER_TO_CLAUDE_MODEL) {
|
|
1389
|
+
_writeText(skill_file, _render_native_model_md(source_file, value));
|
|
1390
|
+
rendered += 1;
|
|
1391
|
+
}
|
|
1392
|
+
else {
|
|
1393
|
+
const rel_target = path.join('../../..', rel_path);
|
|
1394
|
+
fs.symlinkSync(rel_target, skill_file);
|
|
1395
|
+
}
|
|
1396
|
+
count += 1;
|
|
1397
|
+
}
|
|
1398
|
+
let removed_dirs = 0;
|
|
1399
|
+
for (const item of _iterdirSorted(MODULE_STATE.CLAUDE_SKILLS_DIR)) {
|
|
1400
|
+
if (!_isDirNoFollow(item) || _isSymlink(item)) {
|
|
1401
|
+
continue;
|
|
1402
|
+
}
|
|
1403
|
+
const name = path.basename(item);
|
|
1404
|
+
if (skill_names.has(name) || current_slugs.has(name)) {
|
|
1405
|
+
continue;
|
|
1406
|
+
}
|
|
1407
|
+
const skill_md = path.join(item, 'SKILL.md');
|
|
1408
|
+
if (_isSymlink(skill_md) || _isFile(skill_md)) {
|
|
1409
|
+
const entries = _iterdirSorted(item);
|
|
1410
|
+
if (entries.length === 1 && path.basename(entries[0]) === 'SKILL.md') {
|
|
1411
|
+
fs.unlinkSync(skill_md);
|
|
1412
|
+
fs.rmdirSync(item);
|
|
1413
|
+
removed_dirs += 1;
|
|
1414
|
+
}
|
|
1415
|
+
}
|
|
1416
|
+
}
|
|
1417
|
+
let msg = ` ✅ Created ${count} command entries in .claude/skills/`;
|
|
1418
|
+
if (rendered) {
|
|
1419
|
+
msg += ` (${rendered} rendered with native model:)`;
|
|
1420
|
+
}
|
|
1421
|
+
if (skipped) {
|
|
1422
|
+
msg += ` (${skipped} skipped — same-name skill exists)`;
|
|
1423
|
+
}
|
|
1424
|
+
if (removed_dirs) {
|
|
1425
|
+
msg += ` (${removed_dirs} stale dirs removed)`;
|
|
1426
|
+
}
|
|
1427
|
+
info(msg);
|
|
1428
|
+
return count;
|
|
1429
|
+
}
|
|
1430
|
+
/**
|
|
1431
|
+
* Project `src/subagents/*.md` (subagent-v1, ADR-109) → `.claude/agents/*.md`
|
|
1432
|
+
* in Claude Code's native subagent format.
|
|
1433
|
+
*
|
|
1434
|
+
* The source frontmatter carries governance metadata (schema_version, trust,
|
|
1435
|
+
* lifecycle, discovery, source) that Claude Code does not understand; the native
|
|
1436
|
+
* `.claude/agents/` format wants only `{name, description, tools, model}` + the
|
|
1437
|
+
* system-prompt body. This is a **frontmatter transform**, not a symlink:
|
|
1438
|
+
*
|
|
1439
|
+
* - `model_tier` → native `model:` via `_TIER_TO_CLAUDE_MODEL` (ADR-034/035);
|
|
1440
|
+
* the `inherit` sentinel passes through to `model: inherit`.
|
|
1441
|
+
* - `tools` (a YAML list) → the comma-joined form Claude Code accepts.
|
|
1442
|
+
* - the body (everything after the closing `---`) is copied verbatim.
|
|
1443
|
+
*
|
|
1444
|
+
* Static projection only — Claude Code (or the user via `@<name>`) decides
|
|
1445
|
+
* dispatch; nothing here runs an agent. Reads from `src/` directly (subagent
|
|
1446
|
+
* prompts are not telegraph-condensed). Reaps stale generated `.claude/agents/`
|
|
1447
|
+
* files whose source no longer exists.
|
|
1448
|
+
*/
|
|
1449
|
+
export function generate_claude_subagents() {
|
|
1450
|
+
if (!_isDir(MODULE_STATE.SUBAGENTS_SOURCE)) {
|
|
1451
|
+
return 0;
|
|
1452
|
+
}
|
|
1453
|
+
_mkdirp(MODULE_STATE.CLAUDE_AGENTS_DIR);
|
|
1454
|
+
const sources = _rglobSorted(MODULE_STATE.SUBAGENTS_SOURCE, '*.md').filter((p) => _isFile(p));
|
|
1455
|
+
const current = new Set();
|
|
1456
|
+
let count = 0;
|
|
1457
|
+
for (const src of sources) {
|
|
1458
|
+
const stem = path.basename(src, '.md');
|
|
1459
|
+
const text = _readText(src);
|
|
1460
|
+
if (!text.startsWith('---\n')) {
|
|
1461
|
+
continue;
|
|
1462
|
+
}
|
|
1463
|
+
const end = text.indexOf('\n---\n', 4);
|
|
1464
|
+
if (end === -1) {
|
|
1465
|
+
continue;
|
|
1466
|
+
}
|
|
1467
|
+
const fmBlock = text.slice(4, end);
|
|
1468
|
+
const body = text.slice(end + 5);
|
|
1469
|
+
const fm = _yamlParse(fmBlock);
|
|
1470
|
+
if (fm === null) {
|
|
1471
|
+
continue;
|
|
1472
|
+
}
|
|
1473
|
+
const name = typeof fm['name'] === 'string' ? fm['name'] : stem;
|
|
1474
|
+
const description = typeof fm['description'] === 'string' ? fm['description'] : '';
|
|
1475
|
+
const toolsRaw = fm['tools'];
|
|
1476
|
+
const tools = Array.isArray(toolsRaw) ? toolsRaw.map((t) => String(t)).join(', ') : String(toolsRaw ?? '');
|
|
1477
|
+
const tier = typeof fm['model_tier'] === 'string' ? fm['model_tier'] : 'inherit';
|
|
1478
|
+
const model = tier === 'inherit' ? 'inherit' : (_TIER_TO_CLAUDE_MODEL[tier] ?? 'inherit');
|
|
1479
|
+
const out = '---\n' +
|
|
1480
|
+
`name: ${name}\n` +
|
|
1481
|
+
`description: ${description}\n` +
|
|
1482
|
+
`tools: ${tools}\n` +
|
|
1483
|
+
`model: ${model}\n` +
|
|
1484
|
+
'---\n' +
|
|
1485
|
+
body;
|
|
1486
|
+
const target = path.join(MODULE_STATE.CLAUDE_AGENTS_DIR, `${name}.md`);
|
|
1487
|
+
_writeText(target, out);
|
|
1488
|
+
current.add(`${name}.md`);
|
|
1489
|
+
count += 1;
|
|
1490
|
+
}
|
|
1491
|
+
// Reap stale generated agent files (source removed). Only touch plain .md
|
|
1492
|
+
// files we would have generated; never follow into unrelated content.
|
|
1493
|
+
for (const item of _iterdirSorted(MODULE_STATE.CLAUDE_AGENTS_DIR)) {
|
|
1494
|
+
const base = path.basename(item);
|
|
1495
|
+
if (base === 'README.md' || current.has(base)) {
|
|
1496
|
+
continue;
|
|
1497
|
+
}
|
|
1498
|
+
if (_isFile(item) && base.endsWith('.md') && !_isSymlink(item)) {
|
|
1499
|
+
fs.unlinkSync(item);
|
|
1500
|
+
}
|
|
1501
|
+
}
|
|
1502
|
+
info(` ✅ Created ${count} subagent entries in .claude/agents/`);
|
|
1503
|
+
return count;
|
|
1504
|
+
}
|
|
1505
|
+
/**
|
|
1506
|
+
* Cross-host degradation for subagent-v1 (ADR-109 §4).
|
|
1507
|
+
*
|
|
1508
|
+
* Only Claude Code has native subagents (`generate_claude_subagents`). On the
|
|
1509
|
+
* other rules-surface hosts a subagent projects to a **loadable context file** —
|
|
1510
|
+
* a *passive reference*, honestly labelled: there is NO host-native `@`-dispatch
|
|
1511
|
+
* (faking it would need a runtime the package refuses to add). Council
|
|
1512
|
+
* (claude-sonnet-4-5 + gpt-4o, 2026-07-05) converged here over honest-null: the
|
|
1513
|
+
* body is 95% reusable review discipline, 5% dispatch syntax, so an advanced user
|
|
1514
|
+
* on Cursor / Windsurf / Cline loads it on intent and applies the discipline
|
|
1515
|
+
* manually. This is **governance parity, not feature parity** — trust / lifecycle
|
|
1516
|
+
* / model_tier stay legible; automation does not.
|
|
1517
|
+
*
|
|
1518
|
+
* Placement is reaper-safe by construction:
|
|
1519
|
+
* - Cursor / Windsurf → a dedicated `subagents/` subdir with its own reaper,
|
|
1520
|
+
* so it never collides with the aggressive `_clean_modern_dir` rule reapers.
|
|
1521
|
+
* - Cline → a flat real `<name>.subagent.md` in `.clinerules/` (whose reaper
|
|
1522
|
+
* only unlinks *symlinks*, so a real file survives).
|
|
1523
|
+
*
|
|
1524
|
+
* Copilot / Gemini are skipped (no per-file context surface), per ADR-109 §4.
|
|
1525
|
+
* Reads from `src/` directly (subagent prompts are not telegraph-condensed).
|
|
1526
|
+
*/
|
|
1527
|
+
export function generate_subagent_host_contexts() {
|
|
1528
|
+
if (!_isDir(MODULE_STATE.SUBAGENTS_SOURCE)) {
|
|
1529
|
+
return 0;
|
|
1530
|
+
}
|
|
1531
|
+
const sources = _rglobSorted(MODULE_STATE.SUBAGENTS_SOURCE, '*.md').filter((p) => _isFile(p));
|
|
1532
|
+
// Build the passive-reference body once per subagent, keyed by projected name.
|
|
1533
|
+
const rendered = [];
|
|
1534
|
+
for (const src of sources) {
|
|
1535
|
+
const stem = path.basename(src, '.md');
|
|
1536
|
+
const text = _readText(src);
|
|
1537
|
+
if (!text.startsWith('---\n')) {
|
|
1538
|
+
continue;
|
|
1539
|
+
}
|
|
1540
|
+
const end = text.indexOf('\n---\n', 4);
|
|
1541
|
+
if (end === -1) {
|
|
1542
|
+
continue;
|
|
1543
|
+
}
|
|
1544
|
+
const fm = _yamlParse(text.slice(4, end));
|
|
1545
|
+
if (fm === null) {
|
|
1546
|
+
continue;
|
|
1547
|
+
}
|
|
1548
|
+
const body = text.slice(end + 5);
|
|
1549
|
+
const name = typeof fm['name'] === 'string' ? fm['name'] : stem;
|
|
1550
|
+
const description = typeof fm['description'] === 'string' ? fm['description'] : '';
|
|
1551
|
+
// `trust` is either a flat string or the subagent-v1 nested object
|
|
1552
|
+
// {level, confidence, human_review_required}; surface the level either way.
|
|
1553
|
+
const trustRaw = fm['trust'];
|
|
1554
|
+
const trust = typeof trustRaw === 'string'
|
|
1555
|
+
? trustRaw
|
|
1556
|
+
: typeof trustRaw === 'object' && trustRaw !== null && typeof trustRaw['level'] === 'string'
|
|
1557
|
+
? trustRaw['level']
|
|
1558
|
+
: 'unknown';
|
|
1559
|
+
const lifecycle = typeof fm['lifecycle'] === 'string' ? fm['lifecycle'] : 'unknown';
|
|
1560
|
+
const tier = typeof fm['model_tier'] === 'string' ? fm['model_tier'] : 'inherit';
|
|
1561
|
+
const toolsRaw = fm['tools'];
|
|
1562
|
+
const tools = Array.isArray(toolsRaw)
|
|
1563
|
+
? toolsRaw.map((t) => String(t)).join(', ')
|
|
1564
|
+
: String(toolsRaw ?? '');
|
|
1565
|
+
const out = '---\n' +
|
|
1566
|
+
`description: ${description}\n` +
|
|
1567
|
+
'---\n\n' +
|
|
1568
|
+
`# Subagent (passive reference): ${name}\n\n` +
|
|
1569
|
+
'> Passive subagent reference. This host has **no native subagent dispatch** —\n' +
|
|
1570
|
+
`> there is no \`@${name}\` here. Load this discipline manually and apply it.\n` +
|
|
1571
|
+
'> Governance parity (trust / lifecycle / model tier) is preserved below;\n' +
|
|
1572
|
+
'> feature parity is not (ADR-109 §4).\n\n' +
|
|
1573
|
+
`- trust: ${trust}\n` +
|
|
1574
|
+
`- lifecycle: ${lifecycle}\n` +
|
|
1575
|
+
`- model tier: ${tier}\n` +
|
|
1576
|
+
(tools ? `- tools: ${tools}\n` : '') +
|
|
1577
|
+
'\n' +
|
|
1578
|
+
_pyRstrip(body) +
|
|
1579
|
+
'\n';
|
|
1580
|
+
rendered.push({ name, text: out });
|
|
1581
|
+
}
|
|
1582
|
+
// Host targets: [dir, filename(name)->basename, reaper-predicate].
|
|
1583
|
+
const targets = [
|
|
1584
|
+
{
|
|
1585
|
+
active: _tool_active('cursor'),
|
|
1586
|
+
dir: path.join(MODULE_STATE.PROJECT_ROOT, '.cursor', 'subagents'),
|
|
1587
|
+
file: (n) => `${n}.md`,
|
|
1588
|
+
owns: (b) => b.endsWith('.md'),
|
|
1589
|
+
},
|
|
1590
|
+
{
|
|
1591
|
+
active: _tool_active('windsurf'),
|
|
1592
|
+
dir: path.join(MODULE_STATE.PROJECT_ROOT, '.windsurf', 'subagents'),
|
|
1593
|
+
file: (n) => `${n}.md`,
|
|
1594
|
+
owns: (b) => b.endsWith('.md'),
|
|
1595
|
+
},
|
|
1596
|
+
{
|
|
1597
|
+
active: _tool_active('cline'),
|
|
1598
|
+
dir: path.join(MODULE_STATE.PROJECT_ROOT, '.clinerules'),
|
|
1599
|
+
file: (n) => `${n}.subagent.md`,
|
|
1600
|
+
owns: (b) => b.endsWith('.subagent.md'),
|
|
1601
|
+
},
|
|
1602
|
+
];
|
|
1603
|
+
let count = 0;
|
|
1604
|
+
for (const t of targets) {
|
|
1605
|
+
if (!t.active) {
|
|
1606
|
+
continue;
|
|
1607
|
+
}
|
|
1608
|
+
const current = new Set(rendered.map((r) => t.file(r.name)));
|
|
1609
|
+
_mkdirp(t.dir);
|
|
1610
|
+
for (const r of rendered) {
|
|
1611
|
+
_writeText(path.join(t.dir, t.file(r.name)), r.text);
|
|
1612
|
+
count += 1;
|
|
1613
|
+
}
|
|
1614
|
+
// Reap stale generated files we own whose source is gone. Never touch
|
|
1615
|
+
// symlinks (cline's rule symlinks) or a README.
|
|
1616
|
+
if (_exists(t.dir)) {
|
|
1617
|
+
for (const item of _iterdirSorted(t.dir)) {
|
|
1618
|
+
const base = path.basename(item);
|
|
1619
|
+
if (base === 'README.md' || current.has(base)) {
|
|
1620
|
+
continue;
|
|
1621
|
+
}
|
|
1622
|
+
if (_isFile(item) && !_isSymlink(item) && t.owns(base)) {
|
|
1623
|
+
fs.unlinkSync(item);
|
|
1624
|
+
}
|
|
1625
|
+
}
|
|
1626
|
+
}
|
|
1627
|
+
}
|
|
1628
|
+
info(` ✅ Projected ${count} passive subagent context file(s) to non-Claude-Code hosts`);
|
|
1629
|
+
return count;
|
|
1630
|
+
}
|
|
1631
|
+
// Bootstrap shim (road-to-install-path-convergence): the Claude Code plugin
|
|
1632
|
+
// ships ZERO content skills. It carries only hooks/hooks.json (byte-identical
|
|
1633
|
+
// to the managed settings block, so Claude Code dedupes) plus this single
|
|
1634
|
+
// pointer skill whose description names the canonical install command.
|
|
1635
|
+
export const PLUGIN_POINTER_SLUG = 'install-agent-config';
|
|
1636
|
+
export const PLUGIN_POINTER_SKILL_BODY = `---
|
|
1637
|
+
name: install-agent-config
|
|
1638
|
+
description: >-
|
|
1639
|
+
Install or upgrade the event4u agent-config suite. This marketplace plugin
|
|
1640
|
+
is a bootstrap shim — it ships hooks plus this pointer only; ALL skills,
|
|
1641
|
+
rules, and commands are installed via \`npx -y @event4u/agent-config init\`.
|
|
1642
|
+
Use when the user asks to install, set up, or upgrade agent-config, or
|
|
1643
|
+
wonders why this plugin contains no other skills.
|
|
1644
|
+
---
|
|
1645
|
+
|
|
1646
|
+
# Install agent-config
|
|
1647
|
+
|
|
1648
|
+
This plugin is a **bootstrap shim**. It exists so the marketplace listing
|
|
1649
|
+
stays discoverable and existing plugin installs keep working hooks — the
|
|
1650
|
+
content surface (skills, rules, commands, personas) is distributed as a
|
|
1651
|
+
file projection, not through this plugin.
|
|
1652
|
+
|
|
1653
|
+
## Install (canonical, one command)
|
|
1654
|
+
|
|
1655
|
+
\`\`\`bash
|
|
1656
|
+
npx -y @event4u/agent-config init
|
|
1657
|
+
\`\`\`
|
|
1658
|
+
|
|
1659
|
+
The installer writes the full content projection, registers the dispatcher
|
|
1660
|
+
hooks as a managed block in \`~/.claude/settings.json\` (byte-identical to
|
|
1661
|
+
this plugin's hooks, so nothing double-fires), and keeps everything
|
|
1662
|
+
upgradeable via \`agent-config upgrade\`.
|
|
1663
|
+
|
|
1664
|
+
## Already installed both?
|
|
1665
|
+
|
|
1666
|
+
Run \`agent-config doctor\` to check for duplicate surfaces, and
|
|
1667
|
+
\`agent-config converge\` to clean up consented duplicates.
|
|
1668
|
+
`;
|
|
1669
|
+
export function generate_plugin_command_skills() {
|
|
1670
|
+
if (!_isDir(path.join(MODULE_STATE.PROJECT_ROOT, 'src', 'domains'))) {
|
|
1671
|
+
return 0;
|
|
1672
|
+
}
|
|
1673
|
+
_mkdirp(MODULE_STATE.PLUGIN_SKILLS_DIR);
|
|
1674
|
+
// 1. Materialize the pointer skill (idempotent overwrite-on-drift).
|
|
1675
|
+
const pointer_dir = path.join(MODULE_STATE.PLUGIN_SKILLS_DIR, PLUGIN_POINTER_SLUG);
|
|
1676
|
+
_mkdirp(pointer_dir);
|
|
1677
|
+
const pointer_file = path.join(pointer_dir, 'SKILL.md');
|
|
1678
|
+
if (_isSymlink(pointer_file)) {
|
|
1679
|
+
fs.unlinkSync(pointer_file);
|
|
1680
|
+
}
|
|
1681
|
+
if (!_isFile(pointer_file) || fs.readFileSync(pointer_file, 'utf-8') !== PLUGIN_POINTER_SKILL_BODY) {
|
|
1682
|
+
fs.writeFileSync(pointer_file, PLUGIN_POINTER_SKILL_BODY);
|
|
1683
|
+
}
|
|
1684
|
+
// 2. Prune every other skill dir so the tree converges to shim shape
|
|
1685
|
+
// from any prior state. Removable = every entry is a symlink (the
|
|
1686
|
+
// generated projection shape — SKILL.md and optional evals links into
|
|
1687
|
+
// src/), or the dir holds only a single SKILL.md file (the old sweep's
|
|
1688
|
+
// rule). Dirs with real extra files are never touched.
|
|
1689
|
+
let removed_dirs = 0;
|
|
1690
|
+
for (const item of _iterdirSorted(MODULE_STATE.PLUGIN_SKILLS_DIR)) {
|
|
1691
|
+
if (!_isDirNoFollow(item) || _isSymlink(item)) {
|
|
1692
|
+
continue;
|
|
1693
|
+
}
|
|
1694
|
+
if (path.basename(item) === PLUGIN_POINTER_SLUG) {
|
|
1695
|
+
continue;
|
|
1696
|
+
}
|
|
1697
|
+
const entries = _iterdirSorted(item);
|
|
1698
|
+
const all_symlinks = entries.length > 0 && entries.every((e) => _isSymlink(e));
|
|
1699
|
+
const single_skill_md = entries.length === 1 &&
|
|
1700
|
+
path.basename(entries[0]) === 'SKILL.md' &&
|
|
1701
|
+
_isFile(entries[0]);
|
|
1702
|
+
if (all_symlinks || single_skill_md) {
|
|
1703
|
+
for (const e of entries) {
|
|
1704
|
+
fs.unlinkSync(e);
|
|
1705
|
+
}
|
|
1706
|
+
fs.rmdirSync(item);
|
|
1707
|
+
removed_dirs += 1;
|
|
1708
|
+
}
|
|
1709
|
+
}
|
|
1710
|
+
let msg = ' ✅ Plugin skills: bootstrap shim (1 pointer skill) in .claude-plugin/skills/';
|
|
1711
|
+
if (removed_dirs) {
|
|
1712
|
+
msg += ` (${removed_dirs} content entries pruned)`;
|
|
1713
|
+
}
|
|
1714
|
+
info(msg);
|
|
1715
|
+
return 1;
|
|
1716
|
+
}
|
|
1717
|
+
export function generate_persona_symlinks() {
|
|
1718
|
+
if (!_exists(MODULE_STATE.PERSONAS_SOURCE)) {
|
|
1719
|
+
_print(' ⚠️ dist/agent-src/personas/ not found — skipping personas');
|
|
1720
|
+
return 0;
|
|
1721
|
+
}
|
|
1722
|
+
const personas = _rglobSorted(MODULE_STATE.PERSONAS_SOURCE, '*.md')
|
|
1723
|
+
.filter((p) => _isFile(p) && path.basename(p, '.md') !== 'README')
|
|
1724
|
+
.map((p) => path.basename(p))
|
|
1725
|
+
// glob('*.md') is non-recursive in Python; mirror that — only top level.
|
|
1726
|
+
.filter((name) => _isFile(path.join(MODULE_STATE.PERSONAS_SOURCE, name)));
|
|
1727
|
+
// Python uses PERSONAS_SOURCE.glob("*.md") (non-recursive). Re-derive
|
|
1728
|
+
// from a direct listing to match exactly.
|
|
1729
|
+
const direct = _iterdirSorted(MODULE_STATE.PERSONAS_SOURCE)
|
|
1730
|
+
.filter((p) => p.endsWith('.md') && _isFile(p) && path.basename(p, '.md') !== 'README')
|
|
1731
|
+
.map((p) => path.basename(p))
|
|
1732
|
+
.sort((a, b) => (a < b ? -1 : a > b ? 1 : 0));
|
|
1733
|
+
void personas;
|
|
1734
|
+
const list = direct;
|
|
1735
|
+
const tool_dirs = _filter_tool_dirs(PERSONA_TOOL_DIRS);
|
|
1736
|
+
let total = 0;
|
|
1737
|
+
for (const [tool_dir, rel_prefix] of Object.entries(tool_dirs)) {
|
|
1738
|
+
const target_dir = path.join(MODULE_STATE.PROJECT_ROOT, tool_dir);
|
|
1739
|
+
_mkdirp(target_dir);
|
|
1740
|
+
for (const item of _iterdirSorted(target_dir)) {
|
|
1741
|
+
const name = path.basename(item);
|
|
1742
|
+
if (_isSymlink(item) && !list.includes(name) && name !== 'README.md') {
|
|
1743
|
+
fs.unlinkSync(item);
|
|
1744
|
+
}
|
|
1745
|
+
}
|
|
1746
|
+
for (const persona of list) {
|
|
1747
|
+
const link = path.join(target_dir, persona);
|
|
1748
|
+
const target = path.join(rel_prefix, persona);
|
|
1749
|
+
if (_existsOrSymlink(link)) {
|
|
1750
|
+
fs.unlinkSync(link);
|
|
1751
|
+
}
|
|
1752
|
+
fs.symlinkSync(target, link);
|
|
1753
|
+
total += 1;
|
|
1754
|
+
}
|
|
1755
|
+
}
|
|
1756
|
+
info(` ✅ Created ${total} persona symlinks across ${Object.keys(tool_dirs).length} tool directories (${list.length} personas each)`);
|
|
1757
|
+
return total;
|
|
1758
|
+
}
|
|
1759
|
+
export function generate_user_type_symlinks() {
|
|
1760
|
+
if (!_exists(MODULE_STATE.USER_TYPES_SOURCE)) {
|
|
1761
|
+
_print(' ⚠️ dist/agent-src/user-types/ not found — skipping user-types');
|
|
1762
|
+
return 0;
|
|
1763
|
+
}
|
|
1764
|
+
const user_types = _iterdirSorted(MODULE_STATE.USER_TYPES_SOURCE)
|
|
1765
|
+
.filter((p) => p.endsWith('.md') && _isFile(p) && path.basename(p, '.md') !== 'README')
|
|
1766
|
+
.map((p) => path.basename(p))
|
|
1767
|
+
.sort((a, b) => (a < b ? -1 : a > b ? 1 : 0));
|
|
1768
|
+
const tool_dirs = _filter_tool_dirs(USER_TYPE_TOOL_DIRS);
|
|
1769
|
+
let total = 0;
|
|
1770
|
+
for (const [tool_dir, rel_prefix] of Object.entries(tool_dirs)) {
|
|
1771
|
+
const target_dir = path.join(MODULE_STATE.PROJECT_ROOT, tool_dir);
|
|
1772
|
+
_mkdirp(target_dir);
|
|
1773
|
+
for (const item of _iterdirSorted(target_dir)) {
|
|
1774
|
+
const name = path.basename(item);
|
|
1775
|
+
if (_isSymlink(item) && !user_types.includes(name) && name !== 'README.md') {
|
|
1776
|
+
fs.unlinkSync(item);
|
|
1777
|
+
}
|
|
1778
|
+
}
|
|
1779
|
+
for (const user_type of user_types) {
|
|
1780
|
+
const link = path.join(target_dir, user_type);
|
|
1781
|
+
const target = path.join(rel_prefix, user_type);
|
|
1782
|
+
if (_existsOrSymlink(link)) {
|
|
1783
|
+
fs.unlinkSync(link);
|
|
1784
|
+
}
|
|
1785
|
+
fs.symlinkSync(target, link);
|
|
1786
|
+
total += 1;
|
|
1787
|
+
}
|
|
1788
|
+
}
|
|
1789
|
+
info(` ✅ Created ${total} user-type symlinks across ${Object.keys(tool_dirs).length} tool directories (${user_types.length} user-types each)`);
|
|
1790
|
+
return total;
|
|
1791
|
+
}
|
|
1792
|
+
export function generate_plugin_hooks() {
|
|
1793
|
+
const manifest_path = path.join(MODULE_STATE.PROJECT_ROOT, 'src', 'scripts', 'hook_manifest.yaml');
|
|
1794
|
+
if (!_exists(manifest_path)) {
|
|
1795
|
+
process.stderr.write(' ⚠️ scripts/hook_manifest.yaml not found — skipping plugin hooks\n');
|
|
1796
|
+
return 0;
|
|
1797
|
+
}
|
|
1798
|
+
// Single source of truth: the SAME matrix derivation the installer uses
|
|
1799
|
+
// for the managed settings.json block (road-to-claude-code-single-surface
|
|
1800
|
+
// Phase 4) — plugin hooks.json and settings hooks cannot drift by
|
|
1801
|
+
// construction. Backstop: tests/install/claude_hook_matrix_parity.test.ts.
|
|
1802
|
+
const matrix = build_claude_hook_matrix(manifest_path);
|
|
1803
|
+
const hooks = {};
|
|
1804
|
+
for (const [native, command] of Object.entries(matrix)) {
|
|
1805
|
+
hooks[native] = [{ hooks: [{ type: 'command', command }] }];
|
|
1806
|
+
}
|
|
1807
|
+
const hooks_dir = path.join(MODULE_STATE.PROJECT_ROOT, 'hooks');
|
|
1808
|
+
_mkdirp(hooks_dir);
|
|
1809
|
+
const out = path.join(hooks_dir, 'hooks.json');
|
|
1810
|
+
_writeText(out, _jsonDumpsHooks({ hooks }) + '\n');
|
|
1811
|
+
info(` ✅ Generated hooks/hooks.json (${Object.keys(hooks).length} Claude plugin hooks)`);
|
|
1812
|
+
return Object.keys(hooks).length;
|
|
1813
|
+
}
|
|
1814
|
+
/** Mirror json.dumps(obj, indent=2) for the hooks payload (insertion order). */
|
|
1815
|
+
function _jsonDumpsHooks(obj) {
|
|
1816
|
+
return _pyJson(obj, 0);
|
|
1817
|
+
}
|
|
1818
|
+
/**
|
|
1819
|
+
* json.dumps(indent=2) equivalent preserving insertion order, no sort_keys,
|
|
1820
|
+
* ensure_ascii=False is fine here (ASCII content). Matches CPython spacing:
|
|
1821
|
+
* `": "` after keys, `,` newline-separated.
|
|
1822
|
+
*/
|
|
1823
|
+
function _pyJson(value, indent) {
|
|
1824
|
+
const pad = ' '.repeat(indent);
|
|
1825
|
+
const padInner = ' '.repeat(indent + 1);
|
|
1826
|
+
if (Array.isArray(value)) {
|
|
1827
|
+
if (value.length === 0) {
|
|
1828
|
+
return '[]';
|
|
1829
|
+
}
|
|
1830
|
+
const items = value.map((v) => padInner + _pyJson(v, indent + 1));
|
|
1831
|
+
return `[\n${items.join(',\n')}\n${pad}]`;
|
|
1832
|
+
}
|
|
1833
|
+
if (value !== null && typeof value === 'object') {
|
|
1834
|
+
const entries = Object.entries(value);
|
|
1835
|
+
if (entries.length === 0) {
|
|
1836
|
+
return '{}';
|
|
1837
|
+
}
|
|
1838
|
+
const items = entries.map(([k, v]) => `${padInner}${JSON.stringify(k)}: ${_pyJson(v, indent + 1)}`);
|
|
1839
|
+
return `{\n${items.join(',\n')}\n${pad}}`;
|
|
1840
|
+
}
|
|
1841
|
+
return JSON.stringify(value);
|
|
1842
|
+
}
|
|
1843
|
+
function _generate_tools_inner(cmd_slugs, skill_names) {
|
|
1844
|
+
info('🔧 Generating multi-agent tool directories...\n');
|
|
1845
|
+
const rules = generate_rule_symlinks();
|
|
1846
|
+
const windsurfrules = _tool_active('windsurf') ? generate_windsurfrules() : 0;
|
|
1847
|
+
if (_tool_active('gemini')) {
|
|
1848
|
+
generate_gemini_md();
|
|
1849
|
+
}
|
|
1850
|
+
const skills = _tool_active('claude-code') ? generate_claude_skills(skill_names) : 0;
|
|
1851
|
+
const commands = _tool_active('claude-code') ? generate_claude_commands(cmd_slugs) : 0;
|
|
1852
|
+
const subagents = _tool_active('claude-code') ? generate_claude_subagents() : 0;
|
|
1853
|
+
const subagent_contexts = generate_subagent_host_contexts();
|
|
1854
|
+
const plugin_cmd_skills = _tool_active('claude-code') ? generate_plugin_command_skills() : 0;
|
|
1855
|
+
const plugin_hooks = _tool_active('claude-code') ? generate_plugin_hooks() : 0;
|
|
1856
|
+
const personas = generate_persona_symlinks();
|
|
1857
|
+
const user_types = generate_user_type_symlinks();
|
|
1858
|
+
const cursor_mdc = _tool_active('cursor') ? generate_cursor_mdc_rules() : 0;
|
|
1859
|
+
const windsurf_modern = _tool_active('windsurf') ? generate_windsurf_modern_rules() : 0;
|
|
1860
|
+
const cursor_cmds = _tool_active('cursor') ? generate_cursor_commands(cmd_slugs) : 0;
|
|
1861
|
+
const windsurf_wf = _tool_active('windsurf') ? generate_windsurf_workflows(cmd_slugs) : 0;
|
|
1862
|
+
const summary = `✅ generate-tools — rules=${rules} skills=${skills} ` +
|
|
1863
|
+
`commands=${commands} subagents=${subagents} subagent_contexts=${subagent_contexts} plugin_cmd_skills=${plugin_cmd_skills} ` +
|
|
1864
|
+
`plugin_hooks=${plugin_hooks} ` +
|
|
1865
|
+
`personas=${personas} user_types=${user_types} ` +
|
|
1866
|
+
`cursor_mdc=${cursor_mdc} windsurf_rules=${windsurf_modern} ` +
|
|
1867
|
+
`cursor_commands=${cursor_cmds} windsurf_workflows=${windsurf_wf} ` +
|
|
1868
|
+
`windsurfrules=${windsurfrules}`;
|
|
1869
|
+
if (resolve_level() === 'verbose') {
|
|
1870
|
+
_print(`\n${summary}`);
|
|
1871
|
+
}
|
|
1872
|
+
else {
|
|
1873
|
+
success(summary);
|
|
1874
|
+
flush_summary();
|
|
1875
|
+
}
|
|
1876
|
+
}
|
|
1877
|
+
export function generate_tools() {
|
|
1878
|
+
const [cmd_slugs, skill_names] = _resolve_active_predicates();
|
|
1879
|
+
const scoped = cmd_slugs !== null;
|
|
1880
|
+
try {
|
|
1881
|
+
_generate_tools_inner(cmd_slugs, skill_names);
|
|
1882
|
+
}
|
|
1883
|
+
catch (e) {
|
|
1884
|
+
if (scoped) {
|
|
1885
|
+
info(' ⚠️ scoped projection failed — restoring full (legacy-all) projection');
|
|
1886
|
+
_generate_tools_inner(null, null);
|
|
1887
|
+
}
|
|
1888
|
+
throw e;
|
|
1889
|
+
}
|
|
1890
|
+
if (!scoped) {
|
|
1891
|
+
info(' ℹ️ Profile mode available — focused surface. ' +
|
|
1892
|
+
'Run `agent-config use --profile=developer`.');
|
|
1893
|
+
}
|
|
1894
|
+
}
|
|
1895
|
+
// ── .augment/ projection ──────────────────────────────────────────────
|
|
1896
|
+
const AUGMENT_SYMLINK_DIRS = [
|
|
1897
|
+
'skills',
|
|
1898
|
+
'commands',
|
|
1899
|
+
'guidelines',
|
|
1900
|
+
'personas',
|
|
1901
|
+
'user-types',
|
|
1902
|
+
'templates',
|
|
1903
|
+
'contexts',
|
|
1904
|
+
'scripts',
|
|
1905
|
+
];
|
|
1906
|
+
const AUGMENT_SYMLINK_FILES = ['README.md'];
|
|
1907
|
+
export function project_to_augment() {
|
|
1908
|
+
if (!_exists(MODULE_STATE.TARGET_DIR)) {
|
|
1909
|
+
_print(` ⚠️ ${path.basename(MODULE_STATE.TARGET_DIR)}/ not found — nothing to project`);
|
|
1910
|
+
return;
|
|
1911
|
+
}
|
|
1912
|
+
_mkdirp(MODULE_STATE.AUGMENT_DIR);
|
|
1913
|
+
const use_symlinks = _read_augment_rules_use_symlinks();
|
|
1914
|
+
const src_rules = path.join(MODULE_STATE.TARGET_DIR, 'rules');
|
|
1915
|
+
const dst_rules = path.join(MODULE_STATE.AUGMENT_DIR, 'rules');
|
|
1916
|
+
_mkdirp(dst_rules);
|
|
1917
|
+
const existing = new Set(_iterdirSorted(dst_rules)
|
|
1918
|
+
.filter((f) => _isFile(f) || _isSymlink(f))
|
|
1919
|
+
.map((f) => path.basename(f)));
|
|
1920
|
+
const current = new Set();
|
|
1921
|
+
let written = 0;
|
|
1922
|
+
if (_exists(src_rules)) {
|
|
1923
|
+
const rules = _iterdirSorted(src_rules)
|
|
1924
|
+
.filter((p) => p.endsWith('.md') && _isFile(p))
|
|
1925
|
+
.map((p) => path.basename(p))
|
|
1926
|
+
.sort((a, b) => (a < b ? -1 : a > b ? 1 : 0));
|
|
1927
|
+
for (const rule of rules) {
|
|
1928
|
+
const target = path.join(dst_rules, rule);
|
|
1929
|
+
if (_isSymlink(target) || _existsOrSymlink(target)) {
|
|
1930
|
+
fs.unlinkSync(target);
|
|
1931
|
+
}
|
|
1932
|
+
if (use_symlinks) {
|
|
1933
|
+
fs.symlinkSync(path.join('..', '..', 'dist/agent-src', 'rules', rule), target);
|
|
1934
|
+
}
|
|
1935
|
+
else {
|
|
1936
|
+
copy_file(path.join(src_rules, rule), target);
|
|
1937
|
+
}
|
|
1938
|
+
current.add(rule);
|
|
1939
|
+
written += 1;
|
|
1940
|
+
}
|
|
1941
|
+
}
|
|
1942
|
+
let removed_rules = 0;
|
|
1943
|
+
for (const name of existing) {
|
|
1944
|
+
if (!current.has(name)) {
|
|
1945
|
+
fs.unlinkSync(path.join(dst_rules, name));
|
|
1946
|
+
removed_rules += 1;
|
|
1947
|
+
}
|
|
1948
|
+
}
|
|
1949
|
+
const mode_label = use_symlinks ? 'Symlinked' : 'Copied';
|
|
1950
|
+
_print(` ✅ ${mode_label} ${written} rules to .augment/rules/` +
|
|
1951
|
+
(removed_rules ? ` (${removed_rules} stale removed)` : ''));
|
|
1952
|
+
for (const sub of AUGMENT_SYMLINK_DIRS) {
|
|
1953
|
+
const dst = path.join(MODULE_STATE.AUGMENT_DIR, sub);
|
|
1954
|
+
if (_isSymlink(dst) || _existsOrSymlink(dst)) {
|
|
1955
|
+
if (_isDir(dst) && !_isSymlink(dst)) {
|
|
1956
|
+
fs.rmSync(dst, { recursive: true, force: true });
|
|
1957
|
+
}
|
|
1958
|
+
else {
|
|
1959
|
+
fs.unlinkSync(dst);
|
|
1960
|
+
}
|
|
1961
|
+
}
|
|
1962
|
+
const src = path.join(MODULE_STATE.TARGET_DIR, sub);
|
|
1963
|
+
if (_exists(src)) {
|
|
1964
|
+
fs.symlinkSync(path.join('..', 'dist/agent-src', sub), dst);
|
|
1965
|
+
_print(` ✅ Symlinked .augment/${sub} → ../dist/agent-src/${sub}`);
|
|
1966
|
+
}
|
|
1967
|
+
}
|
|
1968
|
+
for (const name of AUGMENT_SYMLINK_FILES) {
|
|
1969
|
+
const dst = path.join(MODULE_STATE.AUGMENT_DIR, name);
|
|
1970
|
+
const src = path.join(MODULE_STATE.TARGET_DIR, name);
|
|
1971
|
+
if (_isSymlink(dst) || _existsOrSymlink(dst)) {
|
|
1972
|
+
fs.unlinkSync(dst);
|
|
1973
|
+
}
|
|
1974
|
+
if (_exists(src)) {
|
|
1975
|
+
fs.symlinkSync(path.join('..', 'dist/agent-src', name), dst);
|
|
1976
|
+
_print(` ✅ Symlinked .augment/${name} → ../dist/agent-src/${name}`);
|
|
1977
|
+
}
|
|
1978
|
+
}
|
|
1979
|
+
const known = new Set([...AUGMENT_SYMLINK_DIRS, ...AUGMENT_SYMLINK_FILES, 'rules', 'state']);
|
|
1980
|
+
for (const item of _iterdirSorted(MODULE_STATE.AUGMENT_DIR)) {
|
|
1981
|
+
const name = path.basename(item);
|
|
1982
|
+
if (known.has(name)) {
|
|
1983
|
+
continue;
|
|
1984
|
+
}
|
|
1985
|
+
if (_isSymlink(item) || _isFile(item)) {
|
|
1986
|
+
fs.unlinkSync(item);
|
|
1987
|
+
_print(` 🗑️ Removed stale .augment/${name}`);
|
|
1988
|
+
}
|
|
1989
|
+
else if (_isDir(item)) {
|
|
1990
|
+
fs.rmSync(item, { recursive: true, force: true });
|
|
1991
|
+
_print(` 🗑️ Removed stale .augment/${name}/`);
|
|
1992
|
+
}
|
|
1993
|
+
}
|
|
1994
|
+
}
|
|
1995
|
+
export function clean_tools() {
|
|
1996
|
+
const targets = [
|
|
1997
|
+
path.join(MODULE_STATE.PROJECT_ROOT, '.claude'),
|
|
1998
|
+
path.join(MODULE_STATE.PROJECT_ROOT, '.cursor'),
|
|
1999
|
+
path.join(MODULE_STATE.PROJECT_ROOT, '.clinerules'),
|
|
2000
|
+
path.join(MODULE_STATE.PROJECT_ROOT, '.windsurf'),
|
|
2001
|
+
path.join(MODULE_STATE.PROJECT_ROOT, '.windsurfrules'),
|
|
2002
|
+
path.join(MODULE_STATE.PROJECT_ROOT, 'GEMINI.md'),
|
|
2003
|
+
];
|
|
2004
|
+
for (const t of targets) {
|
|
2005
|
+
if (_isDirNoFollow(t) && !_isSymlink(t)) {
|
|
2006
|
+
fs.rmSync(t, { recursive: true, force: true });
|
|
2007
|
+
_print(` 🗑️ Removed ${_relativeToPosix(t, MODULE_STATE.PROJECT_ROOT)}`);
|
|
2008
|
+
}
|
|
2009
|
+
else if (_existsOrSymlink(t)) {
|
|
2010
|
+
fs.unlinkSync(t);
|
|
2011
|
+
_print(` 🗑️ Removed ${_relativeToPosix(t, MODULE_STATE.PROJECT_ROOT)}`);
|
|
2012
|
+
}
|
|
2013
|
+
}
|
|
2014
|
+
_print('✅ All generated tool files cleaned');
|
|
2015
|
+
}
|
|
2016
|
+
// --- CLI ---------------------------------------------------------------------
|
|
2017
|
+
/** Plain stdout print mirroring Python's print(). */
|
|
2018
|
+
function _print(line) {
|
|
2019
|
+
process.stdout.write(`${line}\n`);
|
|
2020
|
+
}
|
|
2021
|
+
export function main(argv = process.argv.slice(2)) {
|
|
2022
|
+
if (!_exists(MODULE_STATE.SOURCE_DIR) && !_any_source_root_exists()) {
|
|
2023
|
+
_print(`❌ No source directory found (looked at ${MODULE_STATE.SOURCE_DIR} and packages/*/.agent-src.uncondensed)`);
|
|
2024
|
+
return 1;
|
|
2025
|
+
}
|
|
2026
|
+
const arg = argv.length > 0 ? argv[0] : '--sync';
|
|
2027
|
+
if (arg === '--list') {
|
|
2028
|
+
const files = list_md_files(MODULE_STATE.SOURCE_DIR);
|
|
2029
|
+
_print(`📄 ${files.length} .md files total:\n`);
|
|
2030
|
+
for (const f of files) {
|
|
2031
|
+
_print(` ${f}`);
|
|
2032
|
+
}
|
|
2033
|
+
}
|
|
2034
|
+
else if (arg === '--changed') {
|
|
2035
|
+
const changed = list_changed_md(MODULE_STATE.SOURCE_DIR);
|
|
2036
|
+
if (changed.length === 0) {
|
|
2037
|
+
_print('✅ No .md files changed since last condensation');
|
|
2038
|
+
return 0;
|
|
2039
|
+
}
|
|
2040
|
+
_print(`📝 ${changed.length} .md files changed since last condensation:\n`);
|
|
2041
|
+
for (const f of changed) {
|
|
2042
|
+
_print(` ${f}`);
|
|
2043
|
+
}
|
|
2044
|
+
}
|
|
2045
|
+
else if (arg === '--mark-done') {
|
|
2046
|
+
if (argv.length < 2) {
|
|
2047
|
+
_print('Usage: python scripts/condense.py --mark-done <relative-path>');
|
|
2048
|
+
return 1;
|
|
2049
|
+
}
|
|
2050
|
+
mark_done(argv[1]);
|
|
2051
|
+
}
|
|
2052
|
+
else if (arg === '--mark-all-done') {
|
|
2053
|
+
mark_all_done();
|
|
2054
|
+
}
|
|
2055
|
+
else if (arg === '--check') {
|
|
2056
|
+
const [missing, stale] = check_sync(MODULE_STATE.SOURCE_DIR, MODULE_STATE.TARGET_DIR);
|
|
2057
|
+
if (missing.length === 0 && stale.length === 0) {
|
|
2058
|
+
_print('✅ dist/agent-src/ is in sync with .agent-src.uncondensed/');
|
|
2059
|
+
return 0;
|
|
2060
|
+
}
|
|
2061
|
+
if (missing.length > 0) {
|
|
2062
|
+
_print(`❌ Missing in dist/agent-src/ (${missing.length}):`);
|
|
2063
|
+
for (const f of missing) {
|
|
2064
|
+
_print(` ${f}`);
|
|
2065
|
+
}
|
|
2066
|
+
}
|
|
2067
|
+
if (stale.length > 0) {
|
|
2068
|
+
_print(`❌ Stale in dist/agent-src/ (${stale.length}):`);
|
|
2069
|
+
for (const f of stale) {
|
|
2070
|
+
_print(` ${f}`);
|
|
2071
|
+
}
|
|
2072
|
+
}
|
|
2073
|
+
_print(`\nRun 'task sync' to fix non-.md files, then ask the agent to condense .md files.`);
|
|
2074
|
+
return 1;
|
|
2075
|
+
}
|
|
2076
|
+
else if (arg === '--sync') {
|
|
2077
|
+
_print(`Source: ${MODULE_STATE.SOURCE_DIR}`);
|
|
2078
|
+
_print(`Target: ${MODULE_STATE.TARGET_DIR}\n`);
|
|
2079
|
+
_print('--- Syncing non-.md files ---');
|
|
2080
|
+
const copied = sync_non_md(MODULE_STATE.SOURCE_DIR, MODULE_STATE.TARGET_DIR);
|
|
2081
|
+
_print(`\n--- Cleanup stale files ---`);
|
|
2082
|
+
const deleted = cleanup_stale(MODULE_STATE.SOURCE_DIR, MODULE_STATE.TARGET_DIR);
|
|
2083
|
+
const hashes = load_hashes();
|
|
2084
|
+
const stale_keys = Object.keys(hashes).filter((k) => _resolve_source(k) === null);
|
|
2085
|
+
for (const k of stale_keys) {
|
|
2086
|
+
delete hashes[k];
|
|
2087
|
+
}
|
|
2088
|
+
if (stale_keys.length > 0) {
|
|
2089
|
+
save_hashes(hashes);
|
|
2090
|
+
_print(` Cleaned ${stale_keys.length} stale hash entries`);
|
|
2091
|
+
}
|
|
2092
|
+
const changed = list_changed_md(MODULE_STATE.SOURCE_DIR);
|
|
2093
|
+
_print(`\n✅ Done: ${copied} copied, ${deleted} stale deleted`);
|
|
2094
|
+
if (changed.length > 0) {
|
|
2095
|
+
_print(`📝 ${changed.length} .md files need condensation (run --changed to see them)`);
|
|
2096
|
+
}
|
|
2097
|
+
else {
|
|
2098
|
+
_print(`✅ All .md files are up to date`);
|
|
2099
|
+
}
|
|
2100
|
+
_print(`\n--- Projecting dist/agent-src/ → .augment/ ---`);
|
|
2101
|
+
project_to_augment();
|
|
2102
|
+
}
|
|
2103
|
+
else if (arg === '--check-hashes') {
|
|
2104
|
+
let has_issues = false;
|
|
2105
|
+
const changed = list_changed_md(MODULE_STATE.SOURCE_DIR);
|
|
2106
|
+
const stale = find_stale_hashes(MODULE_STATE.SOURCE_DIR);
|
|
2107
|
+
if (stale.length > 0) {
|
|
2108
|
+
has_issues = true;
|
|
2109
|
+
_print(`⚠️ ${stale.length} stale hash(es) for deleted source files:\n`);
|
|
2110
|
+
for (const f of stale) {
|
|
2111
|
+
_print(` ${f}`);
|
|
2112
|
+
}
|
|
2113
|
+
_print(`\nRun 'task sync-clean-hashes' to remove them.\n`);
|
|
2114
|
+
}
|
|
2115
|
+
if (changed.length > 0) {
|
|
2116
|
+
has_issues = true;
|
|
2117
|
+
_print(`❌ ${changed.length} .md file(s) need recondensation:\n`);
|
|
2118
|
+
for (const f of changed) {
|
|
2119
|
+
const stored = load_hashes()[f];
|
|
2120
|
+
const reason = stored === undefined ? 'no hash stored' : 'hash mismatch';
|
|
2121
|
+
_print(` ${f} (${reason})`);
|
|
2122
|
+
}
|
|
2123
|
+
_print(`\nRun '/condense' command to recondense these files.`);
|
|
2124
|
+
}
|
|
2125
|
+
if (!has_issues) {
|
|
2126
|
+
_print('✅ All condensation hashes are clean (no stale, no mismatches)');
|
|
2127
|
+
return 0;
|
|
2128
|
+
}
|
|
2129
|
+
return 1;
|
|
2130
|
+
}
|
|
2131
|
+
else if (arg === '--clean-hashes') {
|
|
2132
|
+
const count = clean_stale_hashes(MODULE_STATE.SOURCE_DIR);
|
|
2133
|
+
if (count) {
|
|
2134
|
+
_print(`✅ Removed ${count} stale hash(es)`);
|
|
2135
|
+
}
|
|
2136
|
+
else {
|
|
2137
|
+
_print('✅ No stale hashes found');
|
|
2138
|
+
}
|
|
2139
|
+
}
|
|
2140
|
+
else if (arg === '--generate-tools') {
|
|
2141
|
+
generate_tools();
|
|
2142
|
+
}
|
|
2143
|
+
else if (arg === '--clean-tools') {
|
|
2144
|
+
clean_tools();
|
|
2145
|
+
}
|
|
2146
|
+
else if (arg === '--project-augment') {
|
|
2147
|
+
project_to_augment();
|
|
2148
|
+
}
|
|
2149
|
+
else {
|
|
2150
|
+
_print('Usage: python scripts/condense.py [--sync|--list|--changed|--check|--check-hashes|--clean-hashes|--mark-done <path>|--mark-all-done|--generate-tools|--clean-tools|--project-augment]');
|
|
2151
|
+
return 1;
|
|
2152
|
+
}
|
|
2153
|
+
return 0;
|
|
2154
|
+
}
|
|
2155
|
+
function _isCliEntry() {
|
|
2156
|
+
if (process.argv[1] === undefined) {
|
|
2157
|
+
return false;
|
|
2158
|
+
}
|
|
2159
|
+
const argvUrl = pathToFileURL(path.resolve(process.argv[1])).href;
|
|
2160
|
+
if (import.meta.url === argvUrl) {
|
|
2161
|
+
return true;
|
|
2162
|
+
}
|
|
2163
|
+
// A symlinked invocation (e.g. via an installed `.augment/` projection,
|
|
2164
|
+
// or macOS /var → /private/var temp dirs) makes the raw URLs differ:
|
|
2165
|
+
// import.meta.url is the resolved real path while argv[1] keeps the
|
|
2166
|
+
// symlink path. Compare realpaths so the entry guard still fires
|
|
2167
|
+
// (without this the CLI silently no-ops when run through a symlink).
|
|
2168
|
+
try {
|
|
2169
|
+
const here = fs.realpathSync(fileURLToPath(import.meta.url));
|
|
2170
|
+
const argv = fs.realpathSync(path.resolve(process.argv[1]));
|
|
2171
|
+
return here === argv;
|
|
2172
|
+
}
|
|
2173
|
+
catch {
|
|
2174
|
+
return false;
|
|
2175
|
+
}
|
|
2176
|
+
}
|
|
2177
|
+
const isMain = _isCliEntry();
|
|
2178
|
+
if (isMain) {
|
|
2179
|
+
process.exit(main());
|
|
2180
|
+
}
|
|
2181
|
+
//# sourceMappingURL=condense.js.map
|