@darkrymit/crunes-cli 0.4.6 → 0.5.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 (3) hide show
  1. package/README.md +403 -42
  2. package/dist/cli.js +79918 -5394
  3. package/package.json +13 -3
package/README.md CHANGED
@@ -15,17 +15,24 @@ Requires Node.js ≥ 20.
15
15
  ```
16
16
  crunes init Create .crunes/config.json in the current project
17
17
  crunes create [key] Scaffold a new rune and register it in config
18
- crunes use <key> [-a <key>...] Use one or more runes and output the result (use --fail-fast to stop on error)
19
- crunes bench [key] Time rune execution and report performance (use --runs <n> to average)
18
+ crunes use [--section s] <key> [args...] [+ ...] Use one or more runes and output the result (use --fail-fast to stop on error)
19
+ crunes check <key> Run a rune and validate its output shape
20
+ crunes bench <key> Time rune execution and report fast/ok/slow (use --runs <n> to average, --warmup to add a discarded warm-up run)
20
21
  crunes list List all registered runes
22
+ crunes job list List background jobs for the current project
23
+ crunes job kill <id> Send SIGTERM to a job and remove its record (prefix match on id)
24
+ crunes doctor Verify environment and project setup
21
25
  crunes version Print the installed version and check for updates
26
+ crunes docs rune <key...> Show usage, argument schema, and examples for one or more runes
27
+ crunes docs utils [namespaces...] Show function signatures and parameter docs for utils
28
+ crunes completions install <shell> Install shell tab-completion hook (bash, zsh, fish, powershell)
22
29
  ```
23
30
 
24
31
  **Template management:**
25
32
 
26
33
  ```
27
34
  crunes template list [source] List available templates
28
- crunes template use <key> Copy a template into the project as a new rune
35
+ crunes template use [options] <template> Copy a template into the project as a new rune
29
36
  crunes template create [name] Scaffold a new template file
30
37
  ```
31
38
 
@@ -49,6 +56,23 @@ crunes marketplace list List configured sources
49
56
  crunes marketplace search <query> Search for plugins across all sources
50
57
  ```
51
58
 
59
+ **Cache management:**
60
+
61
+ ```
62
+ crunes cache list List all registered cache buckets
63
+ crunes cache clear <id> Remove expired keys from a cache bucket
64
+ crunes cache delete <id> Delete a cache bucket and deregister it
65
+ crunes cache unset <id> <key> Remove a single key from a cache bucket
66
+ ```
67
+
68
+ **SQLite management:**
69
+
70
+ ```
71
+ crunes sqlite list List all registered SQLite databases
72
+ crunes sqlite delete <id> Delete a SQLite database and deregister it
73
+ crunes sqlite query <id> <sql> Run a readonly SQL query against a registered database
74
+ ```
75
+
52
76
  **Global flags:**
53
77
 
54
78
  ```
@@ -72,64 +96,125 @@ crunes marketplace search <query> Search for plugins across all sources
72
96
  cd your-project
73
97
  crunes init # creates .crunes/config.json
74
98
  crunes create docs # scaffolds .crunes/runes/docs.js
75
- crunes use docs # runs the rune and prints output
76
- crunes use docs -a api=v2 # runs multiple runes in batch
99
+ crunes use docs # runs the rune and prints output
100
+ crunes use -b docs + api v2 # runs multiple runes in batch
101
+ ```
102
+
103
+ ### The 3-Tier Parsing Boundary
104
+
105
+ `crunes` parses arguments strictly from left to right in three tiers:
106
+
107
+ 1. **Global Flags** (e.g. `--cwd`, `--verbose`, `-p`) MUST precede the command.
108
+ 2. **Command Flags** (e.g. `-b`, `--format`) MUST immediately follow the command.
109
+ 3. **Rune Arguments** (e.g. `--strict`, `src/`) MUST follow the rune key.
110
+
111
+ ```bash
112
+ # Correct: Global -> Command -> Command Flags -> Rune Key -> Rune Args
113
+ crunes --cwd ./my-project use -b --format json myrune --strict
77
114
  ```
78
115
 
116
+ If you misplace a global flag *after* the command (e.g. `crunes use --cwd ./dir myrune`), the CLI will intercept it and throw a strict validation error to prevent confusing behaviors.
117
+
79
118
  ## Key Syntax
80
119
 
81
- Commands that accept a `<key>` (like `crunes use` and `crunes bench`) support the following syntax:
120
+ Commands that accept a `<key>` (like `crunes use`, `crunes bench`, and `crunes check`) use this syntax:
82
121
 
83
- `[source:]name[=arg1,arg2][::section1,section2]`
122
+ ```
123
+ [-b] [--section s1,s2] [source:]name [rune-arg ...]
124
+ ```
84
125
 
85
126
  - `name`: The name of the rune (auto-resolved from project config first, then plugins).
86
127
  - `source:`: Forces resolution from a specific source.
87
128
  - `local:name` resolves strictly from `.crunes/config.json`.
88
129
  - `my-plugin:name` resolves strictly from an installed plugin.
89
- - `=arg1,arg2`: Passes arguments to the rune (available as `args` in the API).
90
- - `::section1,section2`: Filters the output to only return specific sections.
130
+ - `rune-arg ...`: Everything after the key is passed verbatim to the rune as `args._` (or parsed against the rune's `args()` schema if it exports one). This includes flags — `--verbose`, `--format`, etc.
131
+ - `--section s1,s2`: Filters the output to only include the named sections (must appear before the key).
132
+
133
+ `crunes use` accepts multiple rune segments separated by `+` if you pass the `-b` (batch) flag. Without `-b`, the `+` character is treated as a literal argument passed to the rune!
134
+
135
+ ```bash
136
+ crunes use -b structure + api v2
137
+ crunes use -b --section layout structure + --section files api
138
+ ```
139
+
140
+ **Command-level flags must come before the first key.** The `use` command's own flags (`-b`, `--format`, `--fail-fast`) and `bench`'s flags (`--runs`, `--warmup`) are only recognised at the start of the argument list. Once the parser hits the first key, all remaining tokens (including flags) belong to the rune:
141
+
142
+ ```bash
143
+ # correct — command flags before the key
144
+ crunes use -b --format json mykey --rune-flag val
145
+
146
+ # rune receives --format as its own arg (command format stays 'md')
147
+ crunes use mykey --format custom
148
+ ```
91
149
 
92
150
  ## Rune API
93
151
 
94
- A rune is an ES module that exports a `generate` function:
152
+ A rune is an ES module that exports a `use` function and imports utilities via `@utils`:
95
153
 
96
154
  ```js
97
- export async function generate(dir, args, utils, opts) { ... }
155
+ import { md, section } from '@utils'
156
+
157
+ export async function use(args) {
158
+ // args._ — positional arguments (string[])
159
+ // args.verbose — named flag value (if args() export is defined)
160
+ return section.create('my-section', {
161
+ type: 'markdown',
162
+ content: md.h3('Hello!'),
163
+ })
164
+ }
98
165
  ```
99
166
 
100
- | Parameter | Description |
101
- |---|---|
102
- | `dir` | Absolute path to the project root |
103
- | `args` | `string[]` parsed from `$key=arg1,arg2` tokens |
104
- | `utils` | Injected utilities — see below |
105
- | `opts` | Config options (e.g. `opts.sections` for performance hinting) |
167
+ Every namespace is a named export from `@utils`:
168
+
169
+ ```js
170
+ import { md, tree, section, fs, shell, json, yaml, xml,
171
+ fetch, env, vars, archive, cache, sqlite, crypto, ws, time, rune } from '@utils'
172
+ ```
173
+
174
+ **Typed arguments** — export an `args` function using the builder API:
175
+
176
+ ```js
177
+ export async function args(b) {
178
+ return b
179
+ .option('-v, --verbose', 'Verbose output', false)
180
+ .option('-c, --count <number>', 'Max results', 10)
181
+ .positional('<target>', 'Target path')
182
+ .example('crunes use myrune foo', 'Basic use')
183
+ .build()
184
+ }
185
+ ```
106
186
 
107
187
  ### Return values
108
188
 
109
- **Single section (Shape A):**
189
+ **Single section:**
110
190
 
111
191
  ```js
112
- return { type: 'markdown', content: '...' };
192
+ return section.create('my-section', { type: 'markdown', content: '...' })
113
193
  // or
114
- return { type: 'tree', root: utils.tree.node('src', 'Source root') };
194
+ return section.create('my-section', { type: 'tree', root: tree.node('src', 'Source root') })
115
195
  ```
116
196
 
117
- **Multiple sections (Shape B):**
197
+ **Multiple sections:**
118
198
 
119
199
  ```js
120
200
  return [
121
- utils.section('context', { type: 'markdown', content: '...' }, { title: 'Setup', attrs: { id: 'setup' } }),
122
- utils.section('context', { type: 'tree', root: ... }, { title: 'Structure', attrs: { id: 'structure' } }),
123
- ];
201
+ section.create('setup', { type: 'markdown', content: '...' }),
202
+ section.create('structure', { type: 'tree', root: tree.node('src', 'Source root') }),
203
+ ]
124
204
  ```
125
205
 
126
- ### `utils.md` — Markdown builders
206
+ ---
207
+
208
+ ### `md` — Markdown builders
209
+
210
+ All functions are pure (no I/O).
127
211
 
128
212
  | Function | Output |
129
213
  |---|---|
130
214
  | `md.h1(text)` | `# text\n` |
131
215
  | `md.h2(text)` | `## text\n` |
132
216
  | `md.h3(text)` | `### text\n` |
217
+ | `md.p(text)` | `text\n` |
133
218
  | `md.bold(text)` | `**text**` |
134
219
  | `md.italic(text)` | `_text_` |
135
220
  | `md.code(text)` | `` `text` `` |
@@ -139,49 +224,323 @@ return [
139
224
  | `md.link(text, url)` | `[text](url)` |
140
225
  | `md.table(headers, rows)` | GFM table |
141
226
 
142
- ### `utils.tree` — Tree builders
227
+ ---
228
+
229
+ ### `tree` — Tree builders
230
+
231
+ Pure — no I/O.
143
232
 
144
233
  ```js
145
- utils.tree.node(name, description, children?)
234
+ tree.node(name, description, children?)
146
235
  // → { name, description, children: [] }
147
236
 
148
- utils.tree.format(root, { style: 'tree' | 'list', bullet: '-' | '*' | '+' }?)
237
+ tree.format(root, { style: 'tree' | 'list', bullet: '-' | '*' | '+' }?)
149
238
  // → formatted string
150
239
  ```
151
240
 
152
- ### `utils.section` — Section builder
241
+ ---
242
+
243
+ ### `section` — Section builder
153
244
 
154
245
  ```js
155
- utils.section(name, data, { title?, attrs? }?)
246
+ section.create(name, data, { title?, attrs? }?)
156
247
  // → { name, title, attrs, data }
248
+ // name must be kebab-case; data must be { type: 'markdown', content } or { type: 'tree', root }
249
+
250
+ section.match(name)
251
+ // → boolean — true if name matches the active --section filter (use for early-exit optimisation)
252
+
253
+ section.selected()
254
+ // → string[] | null — the active section filter list, or null if no filter is active
157
255
  ```
158
256
 
159
- ### `utils.fs` — Filesystem access
257
+ ---
258
+
259
+ ### `fs` — Filesystem access
160
260
 
161
- All paths are relative to `dir` and are sandboxed to the project root.
261
+ Permission token: `fs.read:`, `fs.write:`, `fs.glob:` (local runes: unrestricted; plugin runes: declared in `plugin.json`).
162
262
 
163
263
  ```js
164
- await utils.fs.read(relPath, { throw: true }?)
264
+ fs.cwd()
265
+ // → string — absolute path to the project root
266
+
267
+ await fs.read(relPath, { throw: true }?)
165
268
  // → string | null (null only when throw: false and file missing)
166
269
 
167
- await utils.fs.exists(relPath)
270
+ await fs.exists(relPath)
168
271
  // → boolean
169
272
 
170
- await utils.fs.glob(pattern, { ignore?: string[], onlyDirectories?: boolean }?)
171
- // → string[] (forward-slash paths)
273
+ await fs.glob(pattern, { ignore?: string[], onlyDirectories?: boolean, dot?: boolean, expandDirectories?: boolean }?)
274
+ // → string[] (forward-slash paths, relative to project root)
275
+
276
+ await fs.write(relPath, content)
277
+ // → void — creates parent directories automatically
278
+
279
+ await fs.copy(src, dest)
280
+ // → void — creates parent directories automatically; copies a single file
281
+
282
+ await fs.replace(relPath, regex, replacement)
283
+ // → void — reads, applies String.replace(regex, replacement), writes back
172
284
  ```
173
285
 
174
- ### `utils.shell` — Shell commands
286
+ **Path prefixes:**
287
+
288
+ | Prefix | Resolves to |
289
+ |---|---|
290
+ | `relative/path` | Project root |
291
+ | `@project/path` | Project root (explicit alias) |
292
+ | `@plugin/path` | Plugin install directory (plugin runes only) |
293
+ | `~/path` | User home directory |
294
+
295
+ ---
296
+
297
+ ### `shell` — Shell execution
298
+
299
+ Permission token: `shell:<cmd-prefix>` (exact-prefix match against the full command string).
175
300
 
176
301
  ```js
177
- await utils.shell(cmd, { throw: true, trim: true, timeout: 30000, env }?)
178
- // → string (stdout) when trim: true (default)
179
- // → { stdout, stderr, exitCode } when trim: false
302
+ await shell(cmd, { throw?: true, trim?: true, timeout?: 30000, env?: {} }?)
303
+ // → string when trim: true (default) — trimmed stdout
304
+ // → { stdout, stderr, exitCode } when trim: false
180
305
  ```
181
306
 
182
307
  Throws `ShellError` (with `.stdout`, `.stderr`, `.exitCode`) on non-zero exit unless `throw: false`.
183
308
 
184
- > **Plugin runes:** `utils.fs` and `utils.shell` are permission-gated. Allowed patterns are declared in `plugin.json` and shown during consent. Local runes have unrestricted access.
309
+ ---
310
+
311
+ ### `json` — JSON files
312
+
313
+ Inherits `fs.read:` / `fs.write:` permission tokens.
314
+
315
+ ```js
316
+ await json.read(relPath, { throw?: true }?)
317
+ // → object | null
318
+
319
+ await json.get(relPath, jsonPath, defaultValue?)
320
+ // → any — first JSONPath match, or defaultValue
321
+
322
+ await json.getAll(relPath, jsonPath, defaultValue?)
323
+ // → any[] — all JSONPath matches, or defaultValue (default: [])
324
+
325
+ await json.write(relPath, data, { spaces?: 2 }?)
326
+ // → void
327
+
328
+ await json.modify(relPath, async (data, { exists }) => { ... }, { initial?, spaces?: 2 }?)
329
+ // → void — reads file (or uses initial if missing), calls callback, writes result back
330
+ // callback may return a new value or mutate data in place (return undefined = use mutated data)
331
+ // throws if file missing and initial is not provided
332
+ ```
333
+
334
+ ---
335
+
336
+ ### `yaml` — YAML files
337
+
338
+ Inherits `fs.read:` / `fs.write:` permission tokens. Preserves comments and formatting on round-trips.
339
+
340
+ ```js
341
+ await yaml.read(relPath, { throw?: true }?)
342
+ // → object | null
343
+
344
+ await yaml.write(relPath, data, { indent?: 2 }?)
345
+ // → void
346
+
347
+ await yaml.modify(relPath, async (data, { exists }) => { ... }, { initial?, indent?: 2 }?)
348
+ // → void — same semantics as json.modify
349
+ ```
350
+
351
+ ---
352
+
353
+ ### `xml` — XML files
354
+
355
+ Inherits `fs.read:` / `fs.write:` permission tokens. Attributes use `@_` prefix; comments use `#comment`.
356
+
357
+ ```js
358
+ await xml.read(relPath, { throw?: true }?)
359
+ // → object | null
360
+
361
+ await xml.write(relPath, data, { indent?: 2 }?)
362
+ // → void
363
+
364
+ await xml.modify(relPath, async (data, { exists }) => { ... }, { initial?, indent?: 2 }?)
365
+ // → void — same semantics as json.modify
366
+ ```
367
+
368
+ ---
369
+
370
+ ### `fetch` — HTTP client
371
+
372
+ Permission token: `fetch:<METHOD>:<url>` (e.g., `fetch:GET:https://api.example.com/*`).
373
+
374
+ ```js
375
+ const res = await fetch(url, { method?: 'GET', headers?: {}, body?, timeout?: 30000 }?)
376
+ // res.ok — boolean
377
+ // res.status — number
378
+ // res.statusText — string
379
+ // res.headers — object
380
+ // await res.text() — string
381
+ // await res.json() — any
382
+ ```
383
+
384
+ Throws `FetchError` on network errors or timeouts.
385
+
386
+ ---
387
+
388
+ ### `env` — Environment variables
389
+
390
+ Permission token: `env:<source>:<key-glob>` where source is `process` or a `.env` filename (e.g., `env:process:API_*`, `env:.env:*`).
391
+
392
+ ```js
393
+ env.get(key, fallback?)
394
+ // → string | fallback — reads from process.env or .env files per allowed patterns
395
+
396
+ env.has(key)
397
+ // → boolean
398
+ ```
399
+
400
+ ---
401
+
402
+ ### `vars` — Static config values
403
+
404
+ Values come from the `vars` field in `.crunes/config.json` for the rune entry. No permission gate.
405
+
406
+ ```js
407
+ vars.get(key, fallback?)
408
+ // → any
409
+
410
+ vars.has(key)
411
+ // → boolean
412
+ ```
413
+
414
+ ---
415
+
416
+ ### `archive` — Compression
417
+
418
+ Permission tokens: `fs.read:<source>` and `fs.write:<dest>`.
419
+
420
+ ```js
421
+ await archive.unzip(source, dest) // extracts a .zip into dest directory
422
+ await archive.zip(source, dest) // zips a file or directory into dest
423
+ await archive.untar(source, dest) // extracts a .tar.gz into dest directory
424
+ await archive.tar(source, dest) // creates a .tar.gz from a file or directory
425
+ ```
426
+
427
+ Paths are relative to the project root. Zip-slip is detected and rejected.
428
+
429
+ ---
430
+
431
+ ### `cache` — Persistent key-value cache
432
+
433
+ Permission tokens: `cache.read:<location>:<name>` and `cache.write:<location>:<name>`.
434
+
435
+ ```js
436
+ const store = await cache.open(location, name?)
437
+ // location — virtual store token (see below) or relative path
438
+ // name — sub-namespace within the location (default: 'default')
439
+
440
+ await store.set(key, value, ttl?) // ttl in seconds; omit for no expiry
441
+ await store.get(key) // → value | null (expired entries return null)
442
+ await store.delete(key)
443
+ await store.clear() // removes all keys in this store
444
+ ```
445
+
446
+ **Virtual locations:**
447
+
448
+ | Token | Scope |
449
+ |---|---|
450
+ | `@project-cache` | Project-scoped; local runes |
451
+ | `@project-plugin-cache` | Project + plugin scoped (plugin runes) |
452
+ | `@plugin-cache` | Plugin-global across all projects (plugin runes) |
453
+
454
+ Values must be JSON-serializable. Stored as individual `.json` files on disk.
455
+
456
+ ---
457
+
458
+ ### `sqlite` — SQLite databases
459
+
460
+ Permission tokens: `sqlite.read:<location>:<name>` and `sqlite.write:<location>:<name>`.
461
+
462
+ ```js
463
+ const db = await sqlite.open(location, name?)
464
+ // location — virtual store token or relative path
465
+ // name — database filename without extension (default: 'default' → 'default.sqlite')
466
+
467
+ db.query(sql, params?) // → any[] — all matching rows
468
+ db.get(sql, params?) // → any | null — first matching row or null
469
+ db.exec(sql, params?) // → { changes, lastInsertRowid }
470
+ await db.transaction(async () => { ... }) // auto-commits; rolls back on throw
471
+ db.close() // closes the connection (auto-closed at rune exit)
472
+ ```
473
+
474
+ **Virtual locations:**
475
+
476
+ | Token | Scope |
477
+ |---|---|
478
+ | `@project-sqlite` | Project-scoped; local runes |
479
+ | `@project-plugin-sqlite` | Project + plugin scoped (plugin runes) |
480
+ | `@plugin-sqlite` | Plugin-global across all projects (plugin runes) |
481
+
482
+ WAL mode is enabled automatically.
483
+
484
+ ---
485
+
486
+ ### `crypto` — Cryptographic utilities
487
+
488
+ No permission gate. Synchronous.
489
+
490
+ ```js
491
+ crypto.hash.hex(algorithm, data) // → hex string (e.g. algorithm: 'sha256')
492
+ crypto.hash.base64(algorithm, data) // → base64 string
493
+
494
+ crypto.uuid() // → v4 UUID string
495
+ crypto.hex(size) // → hex-encoded random bytes (size = byte count)
496
+ crypto.base64(size) // → base64-encoded random bytes
497
+ ```
498
+
499
+ ---
500
+
501
+ ### `ws` — WebSocket Client
502
+
503
+ Permission token: `ws:<url>`.
504
+
505
+ ```js
506
+ const session = utils.ws.client(url, opts?)
507
+ // session.on(event, handler)
508
+ // await session.open()
509
+ // await session.send(msg)
510
+ // await session.close()
511
+ ```
512
+
513
+ ---
514
+
515
+ ### `time` — Time Utilities
516
+
517
+ No permission gate.
518
+
519
+ ```js
520
+ await time.after(ms) // → Promise that resolves after ms milliseconds
521
+ ```
522
+
523
+ ---
524
+
525
+ ### `rune` — Call other runes
526
+
527
+ Inherits the target rune's permissions. Circular calls throw `CircularRuneError`.
528
+
529
+ ```js
530
+ const sections = await rune.use(key, args?)
531
+ // key — bare key or plugin:key
532
+ // args — string[] of positional arguments
533
+ // → Section[]
534
+
535
+ const job = await rune.spawn(key, args?)
536
+ // → { id, projectKey } — spawns rune in the background
537
+
538
+ await rune.kill(id, signal?)
539
+ // → void — sends signal (default: SIGTERM) to the job
540
+
541
+ const exists = await rune.exists(id)
542
+ // → boolean — true if job process is still running
543
+ ```
185
544
 
186
545
  ## Plugins
187
546
 
@@ -220,7 +579,9 @@ Plugins declare their runes and permissions in `.crunes-plugin/plugin.json`:
220
579
  "runes": {
221
580
  "some-rune": {
222
581
  "permissions": {
223
- "allow": ["fs.read:**", "shell:git log *"]
582
+ "use": {
583
+ "allow": ["fs.read:**", "shell:git log *"]
584
+ }
224
585
  }
225
586
  }
226
587
  }