@leiax00/yushe-agent-kit 0.0.0-stage → 0.1.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.
Files changed (59) hide show
  1. package/.agents/dsh/plugins/yushe-user-rules/README.md +66 -0
  2. package/.agents/dsh/plugins/yushe-user-rules/cordis.patch.yml +5 -0
  3. package/.agents/dsh/plugins/yushe-user-rules/index.js +561 -0
  4. package/.agents/dsh/plugins/yushe-user-rules/package.json +9 -0
  5. package/.agents/rules/docs-management.md +16 -0
  6. package/.agents/rules/git-workflow.md +74 -0
  7. package/.agents/rules/interaction.md +35 -0
  8. package/.agents/skills/yx-api-design/SKILL.md +15 -0
  9. package/.agents/skills/yx-api-design/references/evolution.md +11 -0
  10. package/.agents/skills/yx-api-design/references/http-contract.md +33 -0
  11. package/.agents/skills/yx-api-design/references/idempotency.md +13 -0
  12. package/.agents/skills/yx-backend-architecture/SKILL.md +77 -0
  13. package/.agents/skills/yx-backend-architecture/references/common/clean-design.md +51 -0
  14. package/.agents/skills/yx-backend-architecture/references/common/common.md +31 -0
  15. package/.agents/skills/yx-backend-architecture/references/go/guide.md +9 -0
  16. package/.agents/skills/yx-backend-architecture/references/java/api-layout.md +103 -0
  17. package/.agents/skills/yx-backend-architecture/references/java/coding-style.md +36 -0
  18. package/.agents/skills/yx-backend-architecture/references/java/data-objects.md +68 -0
  19. package/.agents/skills/yx-backend-architecture/references/java/enums-and-constants.md +42 -0
  20. package/.agents/skills/yx-backend-architecture/references/java/framework-boundaries.md +25 -0
  21. package/.agents/skills/yx-backend-architecture/references/java/input-contracts.md +39 -0
  22. package/.agents/skills/yx-backend-architecture/references/java/integrations.md +54 -0
  23. package/.agents/skills/yx-backend-architecture/references/java/logging-and-audit.md +29 -0
  24. package/.agents/skills/yx-backend-architecture/references/java/mybatis-plus.md +65 -0
  25. package/.agents/skills/yx-backend-architecture/references/java/record-vs-class.md +74 -0
  26. package/.agents/skills/yx-backend-architecture/references/java/repositories-and-modules.md +95 -0
  27. package/.agents/skills/yx-backend-architecture/references/java/spring-boot.md +35 -0
  28. package/.agents/skills/yx-backend-architecture/references/java/structure.md +69 -0
  29. package/.agents/skills/yx-backend-architecture/references/java/verification.md +36 -0
  30. package/.agents/skills/yx-backend-architecture/references/python/guide.md +9 -0
  31. package/.agents/skills/yx-backend-architecture/references/typescript/guide.md +9 -0
  32. package/.agents/skills/yx-database-design/SKILL.md +16 -0
  33. package/.agents/skills/yx-database-design/references/engines.md +17 -0
  34. package/.agents/skills/yx-database-design/references/index-and-transactions.md +11 -0
  35. package/.agents/skills/yx-database-design/references/migrations.md +13 -0
  36. package/.agents/skills/yx-database-design/references/modeling.md +13 -0
  37. package/.agents/skills/yx-docs/SKILL.md +32 -0
  38. package/.agents/skills/yx-docs/references/layout.md +102 -0
  39. package/.agents/skills/yx-docs/references/module-docs.md +60 -0
  40. package/.agents/skills/yx-docs/references/notes.md +39 -0
  41. package/.agents/skills/yx-docs/references/reading-protocol.md +25 -0
  42. package/.agents/skills/yx-docs/references/releases.md +63 -0
  43. package/.agents/skills/yx-docs/references/when-to-write.md +33 -0
  44. package/.agents/skills/yx-docs/references/writing-guide.md +80 -0
  45. package/.agents/skills/yx-frontend-architecture/SKILL.md +16 -0
  46. package/.agents/skills/yx-frontend-architecture/references/frameworks.md +15 -0
  47. package/.agents/skills/yx-frontend-architecture/references/state-and-interaction.md +11 -0
  48. package/.agents/skills/yx-frontend-architecture/references/structure.md +11 -0
  49. package/LICENSE +21 -0
  50. package/README.md +76 -2
  51. package/dist/bin/yak.js +11 -0
  52. package/dist/cli/fsx.js +72 -0
  53. package/dist/cli/kit.js +47 -0
  54. package/dist/cli/main.js +132 -0
  55. package/dist/cli/targets/claude.js +47 -0
  56. package/dist/cli/targets/dsh.js +61 -0
  57. package/dist/cli/targets/registry.js +33 -0
  58. package/dist/cli/targets/types.js +1 -0
  59. package/package.json +40 -4
@@ -0,0 +1,66 @@
1
+ # yushe-user-rules
2
+
3
+ Injects project rules into dsh model context with priority across tool
4
+ conventions and optional frontmatter gating.
5
+
6
+ ## Rules directory priority
7
+
8
+ Scanned at the project root (= nearest `.git` ancestor of the session cwd),
9
+ first present wins — later directories are not read:
10
+
11
+ 1. `.agents/rules/`
12
+ 2. `.claude/rules/` (Claude Code)
13
+ 3. `.opencode/rule/` (OpenCode)
14
+ 4. `.cursor/rules/` (Cursor)
15
+
16
+ "Present" means the directory contains at least one rule file, so an empty
17
+ or settings-only `.claude/` does not block the OpenCode or Cursor tiers.
18
+
19
+ ## Rule files
20
+
21
+ Markdown files (`.md`, or Cursor's `.mdc`), recursive; symlinks to files are
22
+ followed, hidden and `node_modules` directories are skipped. Optional YAML
23
+ frontmatter:
24
+
25
+ ```yaml
26
+ ---
27
+ paths:
28
+ - "**/*.ts"
29
+ - "**/*.tsx"
30
+ ---
31
+ ```
32
+
33
+ - **No gate** — injected unconditionally at the session's first model request.
34
+ Cursor's `alwaysApply: true` does the same.
35
+ - **With a gate** — injected at the first model request *after* the agent
36
+ reads, writes, or edits a file matching any glob (project-relative path).
37
+ The key may be `paths` or Cursor's `globs` (whose bare scalar may be a
38
+ comma-separated list). Globs support `**`, `*`, `?`, `{a,b}`, and `[abc]` /
39
+ `[a-z]` / `[!a-z]`; no negation or extglobs. An uncompilable glob falls
40
+ back to unconditional loading with a logged warning.
41
+ - Only gate keys are interpreted (inline array, single scalar, or block dash
42
+ list). Other frontmatter keys are ignored; keep gate lines free of trailing
43
+ comments.
44
+ - Each rule is injected at most once per session; edits mid-session apply to
45
+ the next session.
46
+
47
+ Rendering: files sorted by path, stripped of frontmatter, one
48
+ `<system-reminder>` frame per injection batch, spliced after the direct
49
+ prompt (KV-cache friendly). Budget: 64 KiB per message, 1 MiB per file;
50
+ budget-omitted files are listed in a marker. Subagents get rules for their
51
+ own sessions.
52
+
53
+ ## Install / remove (web profile)
54
+
55
+ ```sh
56
+ dsh plugin --profile web add ~/.dsh/plugins/yushe-user-rules
57
+ dsh plugin --profile web remove yushe-user-rules
58
+ ```
59
+
60
+ Restart the profile after install or edits. Recorded sessions keep their
61
+ historical injected messages and remain replayable.
62
+
63
+ ## Tuning
64
+
65
+ Edit `index.js` top constants: `RULES_ROOTS` (order and candidates),
66
+ `MAX_TOTAL_BYTES`, `MAX_FILE_BYTES`.
@@ -0,0 +1,5 @@
1
+ # Bundle layer for yushe-user-rules. The row references the package by name
2
+ # so Node resolution finds the installed (linked) code.
3
+ - insert:
4
+ - id: yushe-user-rules
5
+ name: yushe-user-rules
@@ -0,0 +1,561 @@
1
+ /**
2
+ * yushe-user-rules — inject project rules into model context from the first
3
+ * present rules directory: `.agents/rules`, then `.claude/rules`, then
4
+ * `.opencode/rule`, then `.cursor/rules` (Claude Code style).
5
+ *
6
+ * Rule files are markdown (`.md`, or Cursor's `.mdc`). An optional YAML
7
+ * frontmatter gate list — `paths`, or Cursor's `globs` — gates a rule: it is
8
+ * injected only after the agent reads, writes, or edits a file matching one
9
+ * of the globs (checked at the next model request). Cursor's
10
+ * `alwaysApply: true` and missing frontmatter load unconditionally at the
11
+ * session's first step. Each rule is injected at most once per session.
12
+ *
13
+ * Mounts on the public `agent/pre-step` waterfall and the `tools/result`
14
+ * event. The agent loop logs injected messages as `user/message`, so no extra
15
+ * persistence work is needed here.
16
+ *
17
+ * Plain ESM with Node-built-in imports only: installed via `dsh plugin add`
18
+ * as a `link:` dependency, whose own dependencies would not be installed, so
19
+ * bare imports must be avoided.
20
+ */
21
+
22
+ import { randomUUID } from 'node:crypto'
23
+ import { readdir, readFile, stat } from 'node:fs/promises'
24
+ import { dirname, isAbsolute, join, relative, resolve, sep } from 'node:path'
25
+
26
+ export const name = 'yushe-user-rules'
27
+ const SOURCE_KIND = 'yushe-user-rules'
28
+ const LEGACY_SOURCE_KIND = 'plugin:yushe-user-rules'
29
+
30
+ /**
31
+ * Candidate rules roots, highest priority first. The first root that yields
32
+ * at least one rule file wins; later roots are not read. An existing but
33
+ * empty root does not win, so a `.claude/` created for settings alone does
34
+ * not block the OpenCode or Cursor tiers.
35
+ */
36
+ const RULES_ROOTS = ['.agents/rules', '.claude/rules', '.opencode/rule', '.cursor/rules']
37
+ /** Maximum UTF-8 bytes of one rendered rules message. */
38
+ const MAX_TOTAL_BYTES = 65536
39
+ /** Bytes reserved for the frame, intro, and budget marker below the total cap. */
40
+ const FRAME_SLACK_BYTES = 512
41
+ /** Maximum UTF-8 bytes read from one rules file; larger files are omitted. */
42
+ const MAX_FILE_BYTES = 1048576
43
+ /** Tool executions whose `file_path` argument counts as a path touch. */
44
+ const TOUCH_TOOLS = new Set(['read', 'write', 'edit'])
45
+
46
+ const FRAME_CLOSE = '</system-reminder>'
47
+ const FRAME_CLOSE_ESCAPED = '<\\/system-reminder>'
48
+ const INTRO = 'The following project rules come from the project root\'s rules directory '
49
+ + `(checked in priority order: ${RULES_ROOTS.join(', ')}; first present wins). `
50
+ + 'Use them as guidance when applicable. They do not override system, developer, or direct user instructions.'
51
+
52
+ function isAbsentError(error) {
53
+ return typeof error === 'object' && error !== null && 'code' in error
54
+ && (error.code === 'ENOENT' || error.code === 'ENOTDIR')
55
+ }
56
+
57
+ function isAbortError(error, signal) {
58
+ return signal?.aborted === true || error?.name === 'AbortError'
59
+ }
60
+
61
+ async function pathExists(path) {
62
+ try {
63
+ await stat(path)
64
+ return true
65
+ } catch (error) {
66
+ if (isAbsentError(error)) return false
67
+ throw error
68
+ }
69
+ }
70
+
71
+ /** Walk upward from `cwd` to the closest directory containing `.git`. */
72
+ async function findProjectRoot(cwd) {
73
+ let current = resolve(cwd)
74
+ for (;;) {
75
+ if (await pathExists(join(current, '.git'))) return current
76
+ const parent = dirname(current)
77
+ if (parent === current) return resolve(cwd)
78
+ current = parent
79
+ }
80
+ }
81
+
82
+ /** Rule file extensions: markdown everywhere, plus Cursor's `.mdc`. */
83
+ function isRuleFileName(fileName) {
84
+ return fileName.endsWith('.md') || fileName.endsWith('.mdc')
85
+ }
86
+
87
+ /**
88
+ * Collect rule files under one rules root, following file symlinks but
89
+ * skipping directory symlinks (loop safety) and hidden or vendored
90
+ * directories (`node_modules`).
91
+ */
92
+ async function collectRuleFiles(dir, out) {
93
+ let entries
94
+ try {
95
+ entries = await readdir(dir, { withFileTypes: true })
96
+ } catch (error) {
97
+ if (isAbsentError(error)) return
98
+ throw error
99
+ }
100
+ for (const entry of entries) {
101
+ const path = join(dir, entry.name)
102
+ if (entry.isDirectory()) {
103
+ if (!entry.name.startsWith('.') && entry.name !== 'node_modules') {
104
+ await collectRuleFiles(path, out)
105
+ }
106
+ continue
107
+ }
108
+ if (!isRuleFileName(entry.name)) continue
109
+ if (entry.isFile()) {
110
+ out.push(path)
111
+ continue
112
+ }
113
+ if (entry.isSymbolicLink()) {
114
+ try {
115
+ if ((await stat(path)).isFile()) out.push(path)
116
+ } catch {
117
+ // A broken or unreadable link is skipped like an absent file.
118
+ }
119
+ }
120
+ }
121
+ }
122
+
123
+ function unquote(value) {
124
+ if (value.length >= 2 && ((value.startsWith('"') && value.endsWith('"'))
125
+ || (value.startsWith("'") && value.endsWith("'")))) {
126
+ return value.slice(1, -1)
127
+ }
128
+ return value
129
+ }
130
+
131
+ /** Split a comma list on top-level commas, honoring quotes and brace depth. */
132
+ function splitCommaList(text) {
133
+ const items = []
134
+ let current = ''
135
+ let quote
136
+ let depth = 0
137
+ for (const ch of text) {
138
+ if (quote !== undefined) {
139
+ current += ch
140
+ if (ch === quote) quote = undefined
141
+ } else if (ch === '"' || ch === "'") {
142
+ quote = ch
143
+ current += ch
144
+ } else if (ch === '{' || ch === '[') {
145
+ depth += 1
146
+ current += ch
147
+ } else if (ch === '}' || ch === ']') {
148
+ depth = Math.max(0, depth - 1)
149
+ current += ch
150
+ } else if (ch === ',' && depth === 0) {
151
+ items.push(current)
152
+ current = ''
153
+ } else {
154
+ current += ch
155
+ }
156
+ }
157
+ items.push(current)
158
+ return items.map(item => unquote(item.trim())).filter(item => item.length > 0)
159
+ }
160
+
161
+ /**
162
+ * Extract the frontmatter gate list from YAML text. The `paths` key is the
163
+ * native form; Cursor's `globs` key is accepted as an alias whose bare scalar
164
+ * may be a comma-separated list. Supported shapes: inline array, single
165
+ * scalar, and block dash lists. Other keys are ignored. @returns whether a
166
+ * gate key is present and its string list.
167
+ */
168
+ function parsePathsField(yamlText) {
169
+ const lines = yamlText.split(/\r?\n/)
170
+ for (let i = 0; i < lines.length; i += 1) {
171
+ const match = lines[i].match(/^\s*(paths|globs)\s*:\s*(.*)$/)
172
+ if (match === null) continue
173
+ const inline = match[2].trim()
174
+ if (inline.length > 0) {
175
+ if (inline.startsWith('[')) {
176
+ const inner = inline.replace(/^\[/, '').replace(/\]$/, '').trim()
177
+ if (inner.length === 0) return { present: true, globs: [] }
178
+ return { present: true, globs: splitCommaList(inner) }
179
+ }
180
+ if (match[1] === 'globs') {
181
+ // Cursor allows a bare comma-separated scalar for its globs key.
182
+ return { present: true, globs: splitCommaList(inline) }
183
+ }
184
+ return { present: true, globs: [unquote(inline)] }
185
+ }
186
+ const globs = []
187
+ for (let j = i + 1; j < lines.length; j += 1) {
188
+ const item = lines[j].match(/^\s+-\s*(.*)$/)
189
+ if (item === null) break
190
+ const value = unquote(item[1].trim())
191
+ if (value.length > 0) globs.push(value)
192
+ }
193
+ return { present: true, globs }
194
+ }
195
+ return { present: false, globs: undefined }
196
+ }
197
+
198
+ /**
199
+ * Whether the frontmatter sets a boolean key to true; Cursor's
200
+ * `alwaysApply: true` forces unconditional loading.
201
+ */
202
+ function parseBooleanTrue(yamlText, key) {
203
+ for (const line of yamlText.split(/\r?\n/)) {
204
+ const match = line.match(new RegExp(`^\\s*${key}\\s*:\\s*(.*)$`))
205
+ if (match === null) continue
206
+ return unquote(match[1].trim()).toLowerCase() === 'true'
207
+ }
208
+ return false
209
+ }
210
+
211
+ /**
212
+ * Split a leading `---` YAML frontmatter block. @returns the block's YAML
213
+ * text (without markers) and the body; both empty/absent when no block.
214
+ */
215
+ function splitFrontmatter(raw) {
216
+ if (!raw.startsWith('---\n') && !raw.startsWith('---\r\n')) return { yaml: undefined, body: raw }
217
+ let lineStart = raw.indexOf('\n') + 1
218
+ while (lineStart <= raw.length) {
219
+ const nextNewline = raw.indexOf('\n', lineStart)
220
+ const lineEnd = nextNewline < 0 ? raw.length : nextNewline
221
+ const line = raw.slice(lineStart, lineEnd).replace(/\r$/, '')
222
+ if (line === '---') {
223
+ return {
224
+ yaml: raw.slice(raw.indexOf('\n') + 1, lineStart - 1),
225
+ body: raw.slice(nextNewline < 0 ? raw.length : nextNewline + 1),
226
+ }
227
+ }
228
+ if (nextNewline < 0) return { yaml: undefined, body: raw }
229
+ lineStart = nextNewline + 1
230
+ }
231
+ return { yaml: undefined, body: raw }
232
+ }
233
+
234
+ const globCache = new Map()
235
+
236
+ function escapeLiteral(ch) {
237
+ return /[.*+?^${}()|[\]\\]/.test(ch) ? `\\${ch}` : ch
238
+ }
239
+
240
+ /**
241
+ * Compile one glob to a RegExp over project-relative POSIX paths. Supported:
242
+ * a double-star segment (any number of directories, zero included when it
243
+ * precedes a slash), single-star within one segment, a single-character
244
+ * wildcard, brace alternations, and bracket character classes. No negation
245
+ * or extglobs.
246
+ */
247
+ function compileGlob(pattern) {
248
+ let compiled = globCache.get(pattern)
249
+ if (compiled === undefined) {
250
+ compiled = new RegExp(`^${compileGlobSource(pattern)}$`)
251
+ globCache.set(pattern, compiled)
252
+ }
253
+ return compiled
254
+ }
255
+
256
+ /** Compile a glob to an unanchored RegExp source. */
257
+ function compileGlobSource(pattern) {
258
+ let source = ''
259
+ let i = 0
260
+ while (i < pattern.length) {
261
+ const ch = pattern[i]
262
+ if (ch === '{') {
263
+ const close = pattern.indexOf('}', i)
264
+ if (close < 0) {
265
+ source += escapeLiteral(ch)
266
+ i += 1
267
+ continue
268
+ }
269
+ const alternatives = pattern.slice(i + 1, close)
270
+ .split(',')
271
+ .map(alternative => compileGlobSource(alternative))
272
+ source += `(?:${alternatives.join('|')})`
273
+ i = close + 1
274
+ continue
275
+ }
276
+ if (ch === '[') {
277
+ const close = pattern.indexOf(']', i + 1)
278
+ if (close < 0) {
279
+ source += escapeLiteral(ch)
280
+ i += 1
281
+ continue
282
+ }
283
+ let body = pattern.slice(i + 1, close)
284
+ let negated = ''
285
+ if (body.startsWith('!')) {
286
+ negated = '^'
287
+ body = body.slice(1)
288
+ }
289
+ body = body.replace(/\\/g, '\\\\').replace(/\^/g, '\\^')
290
+ source += `[${negated}${body}]`
291
+ i = close + 1
292
+ continue
293
+ }
294
+ if (ch === '*') {
295
+ let j = i + 1
296
+ while (pattern[j] === '*') j += 1
297
+ if (j > i + 1) {
298
+ if (pattern[j] === '/') {
299
+ // A `**/` boundary matches zero or more whole segments.
300
+ source += '(?:[^/]*/)*'
301
+ i = j + 1
302
+ } else {
303
+ source += '.*'
304
+ i = j
305
+ }
306
+ continue
307
+ }
308
+ source += '[^/]*'
309
+ i += 1
310
+ continue
311
+ }
312
+ if (ch === '?') {
313
+ source += '[^/]'
314
+ i += 1
315
+ continue
316
+ }
317
+ source += escapeLiteral(ch)
318
+ i += 1
319
+ }
320
+ return source
321
+ }
322
+
323
+ /** One parsed rules file; `matchers` is `undefined` for ungated rules. */
324
+ function parseRuleFile(root, path, raw, warn) {
325
+ const { yaml, body } = splitFrontmatter(raw)
326
+ const content = body.trim()
327
+ if (content.length === 0) return undefined
328
+ let globs
329
+ if (yaml !== undefined) {
330
+ if (parseBooleanTrue(yaml, 'alwaysApply')) {
331
+ globs = undefined
332
+ } else {
333
+ const parsed = parsePathsField(yaml)
334
+ if (parsed.present) {
335
+ try {
336
+ globs = parsed.globs.map(pattern => compileGlob(pattern))
337
+ } catch (error) {
338
+ // An uncompilable glob must not silently hide the rule; load it
339
+ // unconditionally and say so.
340
+ warn(`yushe-user-rules: paths glob in ${relative(root, path)} failed to compile (${String(error)}); rule loads unconditionally`)
341
+ globs = undefined
342
+ }
343
+ }
344
+ }
345
+ }
346
+ const displayPath = relative(root, path)
347
+ return {
348
+ displayPath,
349
+ relPath: displayPath.split(sep).join('/'),
350
+ body: content,
351
+ globs,
352
+ }
353
+ }
354
+
355
+ /** Discover and parse every rule file for one project. @returns parsed rules. */
356
+ async function scanRules(cwd, signal, warn) {
357
+ let root
358
+ try {
359
+ root = await findProjectRoot(cwd)
360
+ } catch (error) {
361
+ warn(`yushe-user-rules: failed to locate project root: ${String(error)}`)
362
+ return { root: resolve(cwd), rules: [] }
363
+ }
364
+ const files = []
365
+ for (const dir of RULES_ROOTS) {
366
+ const collected = []
367
+ try {
368
+ await collectRuleFiles(join(root, dir), collected)
369
+ } catch (error) {
370
+ warn(`yushe-user-rules: failed to scan ${dir}: ${String(error)}`)
371
+ }
372
+ // First-match-wins: stop before consulting lower-priority roots.
373
+ if (collected.length > 0) {
374
+ files.push(...collected)
375
+ break
376
+ }
377
+ }
378
+ files.sort()
379
+ const rules = []
380
+ for (const path of files) {
381
+ let raw
382
+ try {
383
+ raw = await readFile(path, { encoding: 'utf8', signal })
384
+ } catch (error) {
385
+ if (isAbortError(error, signal)) return { root, rules }
386
+ warn(`yushe-user-rules: failed to read ${path}: ${String(error)}`)
387
+ continue
388
+ }
389
+ if (Buffer.byteLength(raw, 'utf8') > MAX_FILE_BYTES) continue
390
+ const rule = parseRuleFile(root, path, raw, warn)
391
+ if (rule !== undefined) rules.push(rule)
392
+ }
393
+ return { root, rules }
394
+ }
395
+
396
+ function escapeFrameClose(text) {
397
+ return text.replaceAll(FRAME_CLOSE, FRAME_CLOSE_ESCAPED)
398
+ }
399
+
400
+ /**
401
+ * Render one injection batch: `due` rules in the given order, byte-budgeted.
402
+ * @returns framed text plus the display paths actually represented.
403
+ */
404
+ function renderBatch(due) {
405
+ const sections = []
406
+ const omitted = []
407
+ const included = []
408
+ let usedBytes = 0
409
+ for (const rule of due) {
410
+ const heading = rule.globs === undefined
411
+ ? `Rules from: ${rule.displayPath}`
412
+ : `Rules from: ${rule.displayPath} (apply to work on files matching their paths globs)`
413
+ const section = `${heading}\n\n${rule.body}`
414
+ const sectionBytes = Buffer.byteLength(section, 'utf8')
415
+ if (usedBytes + sectionBytes > MAX_TOTAL_BYTES - FRAME_SLACK_BYTES) {
416
+ omitted.push(rule.displayPath)
417
+ continue
418
+ }
419
+ usedBytes += sectionBytes
420
+ sections.push(section)
421
+ included.push(rule.displayPath)
422
+ }
423
+ if (included.length === 0) return undefined
424
+ const parts = [INTRO, ...sections]
425
+ if (omitted.length > 0) {
426
+ parts.push(`Rules budget ${MAX_TOTAL_BYTES} bytes: omitted ${omitted.join(', ')}`)
427
+ }
428
+ return {
429
+ text: `<system-reminder>\n${escapeFrameClose(parts.join('\n\n'))}\n${FRAME_CLOSE}`,
430
+ included,
431
+ }
432
+ }
433
+
434
+ /** Rule paths already carried by this session's visible history. */
435
+ async function suppliedFromHistory(session, warn) {
436
+ try {
437
+ const derived = session.deriveMessages()
438
+ const list = derived instanceof Promise ? await derived : derived
439
+ const supplied = new Set()
440
+ if (Array.isArray(list)) {
441
+ for (const message of list) {
442
+ const source = message?.source
443
+ if (message?.role === 'user' && (source?.kind === SOURCE_KIND || source?.kind === LEGACY_SOURCE_KIND)
444
+ && Array.isArray(source.rules)) {
445
+ for (const path of source.rules) {
446
+ if (typeof path === 'string') supplied.add(path)
447
+ }
448
+ }
449
+ }
450
+ }
451
+ return supplied
452
+ } catch (error) {
453
+ // History inspection guards against duplicate injection across restarts;
454
+ // on failure prefer injecting over silently dropping rules.
455
+ warn(`yushe-user-rules: could not inspect session history: ${String(error)}`)
456
+ return new Set()
457
+ }
458
+ }
459
+
460
+ function filePathFromExecution(exec) {
461
+ if (!TOUCH_TOOLS.has(exec.name)) return undefined
462
+ if (typeof exec.arguments !== 'object' || exec.arguments === null) return undefined
463
+ if (typeof exec.arguments.file_path !== 'string') return undefined
464
+ const filePath = exec.arguments.file_path.trim()
465
+ return filePath.length > 0 ? filePath : undefined
466
+ }
467
+
468
+ /**
469
+ * Register baseline and path-gated rules injection. Rules are supplied at
470
+ * most once per session; edits mid-session apply to the next session.
471
+ */
472
+ export function apply(ctx) {
473
+ const warn = message => ctx.logger?.warn(message)
474
+ const sessions = new WeakMap()
475
+
476
+ const stateOf = session => {
477
+ let state = sessions.get(session)
478
+ if (state === undefined) {
479
+ state = {
480
+ cwd: session.header?.cwd ?? process.cwd(),
481
+ root: undefined,
482
+ rules: undefined,
483
+ historyScanned: false,
484
+ supplied: new Set(),
485
+ pending: new Set(),
486
+ }
487
+ sessions.set(session, state)
488
+ }
489
+ return state
490
+ }
491
+
492
+ const ensureRules = async (state, signal) => {
493
+ if (state.rules === undefined) {
494
+ const { root, rules } = await scanRules(state.cwd, signal, warn)
495
+ state.root = root
496
+ state.rules = rules
497
+ }
498
+ return state.rules
499
+ }
500
+
501
+ ctx.on('tools/result', (exec, result) => {
502
+ if (result.isError || exec.agent === undefined || exec.signal?.aborted) return
503
+ const filePath = filePathFromExecution(exec)
504
+ if (filePath === undefined) return
505
+ const state = stateOf(exec.agent.session)
506
+ const rules = state.rules ?? undefined
507
+ if (rules === undefined) {
508
+ // Discovery is deferred to the first pre-step; touches before it only
509
+ // matter once rules are known, and pre-step follows before the next
510
+ // request anyway.
511
+ return
512
+ }
513
+ const relPath = relative(state.root, resolve(state.cwd, filePath))
514
+ if (relPath.length === 0 || relPath === '..' || relPath.startsWith(`..${sep}`) || isAbsolute(relPath)) return
515
+ const posix = relPath.split(sep).join('/')
516
+ for (const rule of rules) {
517
+ if (rule.globs === undefined || state.supplied.has(rule.displayPath) || state.pending.has(rule.displayPath)) continue
518
+ if (rule.globs.some(matcher => matcher.test(posix))) state.pending.add(rule.displayPath)
519
+ }
520
+ })
521
+
522
+ ctx.on('agent/pre-step', async ({ agent, messages, signal }, next) => {
523
+ const decision = await next()
524
+ if (decision.kind !== 'enter' || decision.messages.length === 0) return decision
525
+ const session = agent?.session
526
+ if (session === undefined) return decision
527
+ const state = stateOf(session)
528
+ if (!state.historyScanned) {
529
+ state.supplied = await suppliedFromHistory(session, warn)
530
+ state.historyScanned = true
531
+ }
532
+ const rules = await ensureRules(state, signal)
533
+ if (rules.length === 0 && state.pending.size === 0) return decision
534
+ const byPath = new Map(rules.map(rule => [rule.displayPath, rule]))
535
+ const due = [
536
+ ...rules.filter(rule => rule.globs === undefined && !state.supplied.has(rule.displayPath)),
537
+ ...[...state.pending].flatMap(path => {
538
+ const rule = byPath.get(path)
539
+ return rule !== undefined && !state.supplied.has(rule.displayPath) ? [rule] : []
540
+ }),
541
+ ]
542
+ if (due.length === 0) return decision
543
+ const batch = renderBatch(due)
544
+ state.pending.clear()
545
+ // Mark the whole batch supplied so budget-omitted rules do not retry on
546
+ // every following step.
547
+ for (const rule of due) state.supplied.add(rule.displayPath)
548
+ if (batch === undefined) return decision
549
+ const desired = Object.freeze({
550
+ id: randomUUID(),
551
+ role: 'user',
552
+ content: Object.freeze([{ type: 'text', text: batch.text }]),
553
+ source: Object.freeze({ kind: SOURCE_KIND, rules: Object.freeze([...batch.included]) }),
554
+ })
555
+ // Splice after the last claimed message so the direct prompt prefix stays
556
+ // stable for KV caching.
557
+ const last = decision.messages.findLastIndex(message => messages.includes(message))
558
+ const at = last >= 0 ? last + 1 : decision.messages.length
559
+ return { ...decision, messages: decision.messages.toSpliced(at, 0, desired) }
560
+ })
561
+ }
@@ -0,0 +1,9 @@
1
+ {
2
+ "name": "yushe-user-rules",
3
+ "version": "0.3.0",
4
+ "description": "Inject project rules (.agents > .claude > .opencode > .cursor, first present wins) into dsh model context, with paths/globs frontmatter gating",
5
+ "type": "module",
6
+ "main": "index.js",
7
+ "files": ["index.js", "cordis.patch.yml", "README.md"],
8
+ "dsh": { "bundle": { "patch": "./cordis.patch.yml" } }
9
+ }
@@ -0,0 +1,16 @@
1
+ ---
2
+ paths:
3
+ - "**/*.md"
4
+ - "**/*.mdx"
5
+ ---
6
+
7
+ # 文档管理底线
8
+
9
+ 完整的布局约定、模块文档模板、决策记录与变更记录规范由 `yx-docs` Skill 承载(涉及文档结构、查找、编写时加载);本规则只保留强制底线:
10
+
11
+ 1. 不在仓库根目录堆积散装 md 文件(MUST NOT,可能被 agent 工具误识别为技能入口);文档按 `yx-docs` 的布局约定放置。
12
+ 2. 移动或重命名文档时 MUST 同步更新所有引用链接。
13
+ 3. 同一规则/事实只在一处定义,其他位置放链接。
14
+ 4. 代码相关的描述与代码冲突时以代码为准,不凭记忆改写技术细节。
15
+ 5. 中文为主,代码示例、专有名词保留英文;不冒充外部规范原文,未验证的内容不写成已验证。
16
+ 6. 修改文档的提交用 `docs:` 前缀(见 git-workflow 规则)。