@rhizogrip/spore-cli 0.0.0-stage → 1.0.1

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/src/doctor.js ADDED
@@ -0,0 +1,75 @@
1
+ import { doctor, loadMohdelEnvironment, modelFindings } from '@rhizogrip/spore'
2
+
3
+ import { createServices } from './services.js'
4
+
5
+ const AREAS = ['operator', 'spores', 'models', 'plugins', 'services', 'machine']
6
+
7
+ /**
8
+ * A place `<kind>:<instance>/…` is served by the service `<kind>@<instance>` — `telegram:triage/42`
9
+ * by `telegram@triage` — so a default reply-to, or answers waiting in an outbox, name the service
10
+ * that has to be running for them to arrive. A place of no such shape names none.
11
+ */
12
+ function servedBy (recipient) {
13
+ const named = /^([a-z][a-z0-9-]*):([^/]+)\//.exec(recipient)
14
+ return named && `${named[1]}@${named[2]}`
15
+ }
16
+
17
+ function serviceFindings (services, needsTick, replies) {
18
+ const findings = []
19
+ const problem = (subject, what, fix) => findings.push({ area: 'services', subject, severity: 'problem', problem: what, fix })
20
+ const note = (subject, what, fix) => findings.push({ area: 'services', subject, severity: 'note', problem: what, fix })
21
+ let listed
22
+ try {
23
+ listed = services.list()
24
+ } catch (err) {
25
+ if (err.type !== 'SERVICE_NO_SYSTEMD') throw err
26
+ if (needsTick.length) problem('tick', `${needsTick.join(', ')}, and there is no systemd user session to run the tick timer`, 'run spore tick every minute some other way')
27
+ return findings
28
+ }
29
+ for (const { plugin, problem: what } of listed.problems) problem(`plugin ${plugin}`, `offers no service: ${what}`, `fix or uninstall ${plugin}`)
30
+ for (const row of listed.services) {
31
+ if (row.foreign) problem(row.name, `${row.foreign} was not written by spore`, `remove it, then spore service define ${row.name}`)
32
+ if (!row.defined) continue
33
+ for (const gone of row.stale) problem(row.name, `its unit starts ${gone}, which is gone`, `spore service define ${row.name}`)
34
+ if (row.unitChanged) problem(row.name, `pid ${row.pid} runs what its unit named before it was last written`, `spore service restart ${row.name}`)
35
+ if (row.outdated) problem(row.name, `runs ${row.outdated.from} ${row.outdated.running}, and ${row.outdated.installed} is installed`, `spore service restart ${row.name}`)
36
+ if (row.enabled && row.active !== 'active') problem(row.name, `is enabled and ${row.active} (${row.sub})`, `spore service log ${row.name}`)
37
+ if (row.restarts) note(row.name, `systemd has restarted it ${row.restarts} time${row.restarts > 1 ? 's' : ''}`, `spore service log ${row.name}`)
38
+ }
39
+ const tick = listed.services.find(row => row.name === 'tick')
40
+ if (needsTick.length && !(tick.defined && tick.active === 'active')) {
41
+ problem('tick', `${needsTick.join(', ')}, and the tick timer is ${tick.defined ? tick.active : 'not defined'} — nothing fires them`, tick.defined ? 'spore service enable tick, then spore service start tick' : 'spore service define tick, then enable and start it')
42
+ }
43
+ if (!listed.linger && listed.services.some(row => row.enabled)) note('linger', 'is off, so every service stops when you log out', 'loginctl enable-linger')
44
+ for (const { spore, recipient, waiting } of replies) {
45
+ const name = servedBy(recipient)
46
+ if (!name) continue
47
+ const row = listed.services.find(each => each.name === name)
48
+ if (row?.defined && row.active === 'active') continue
49
+ const is = !row ? 'no service here' : row.defined ? row.active : 'not defined'
50
+ const fix = !row ? `install the plugin that serves ${name.split('@')[0]}, or change where ${spore} answers` : row.defined ? `spore service start ${name}` : `spore service define ${name}, then start it`
51
+ problem(name, waiting ? `${waiting} answer${waiting > 1 ? 's' : ''} of ${spore} wait for it to deliver them, and it is ${is}` : `${spore} answers to ${recipient} by default, and ${name} is ${is}`, fix)
52
+ }
53
+ return findings
54
+ }
55
+
56
+ export async function diagnose ({ services = createServices() } = {}) {
57
+ loadMohdelEnvironment()
58
+ const { findings, needsTick, replies } = doctor()
59
+ return { findings: [...findings, ...await modelFindings(), ...serviceFindings(services, needsTick, replies)] }
60
+ }
61
+
62
+ export function renderDoctor ({ findings }) {
63
+ for (const area of AREAS) {
64
+ const here = findings.filter(found => found.area === area)
65
+ if (!here.length) continue
66
+ console.log(area)
67
+ for (const found of here) {
68
+ console.log(` ${found.severity === 'note' ? 'note: ' : ''}${found.subject} — ${found.problem}`)
69
+ if (found.fix) console.log(` ${found.fix}`)
70
+ }
71
+ }
72
+ const problems = findings.filter(found => found.severity === 'problem').length
73
+ const notes = findings.length - problems
74
+ console.log(findings.length ? `\n${problems} problem${problems === 1 ? '' : 's'}, ${notes} note${notes === 1 ? '' : 's'}` : 'nothing wrong')
75
+ }
package/src/here.js ADDED
@@ -0,0 +1,105 @@
1
+ /**
2
+ * `spore here`: the spore a directory is worked in by, and git as its undo. A session's start is
3
+ * a commit of the directory as it stands — tracked and untracked files, `.gitignore` respected —
4
+ * written through an index of its own, so neither the work tree nor the user's index moves.
5
+ */
6
+
7
+ import { execFileSync } from 'node:child_process'
8
+ import { createHash } from 'node:crypto'
9
+ import { mkdtempSync, rmSync, unlinkSync } from 'node:fs'
10
+ import { tmpdir } from 'node:os'
11
+ import { basename, join, relative } from 'node:path'
12
+
13
+ const IDENTITY = { GIT_AUTHOR_NAME: 'spore', GIT_AUTHOR_EMAIL: 'spore@localhost', GIT_COMMITTER_NAME: 'spore', GIT_COMMITTER_EMAIL: 'spore@localhost' }
14
+
15
+ export function sporeNameFor (dir) {
16
+ const readable = basename(dir).replace(/[^A-Za-z0-9._-]+/g, '-').replace(/^[^A-Za-z0-9]+/, '').slice(0, 48) || 'root'
17
+ return `${readable}-${createHash('sha256').update(dir).digest('hex').slice(0, 6)}`
18
+ }
19
+
20
+ const git = (cwd, args, env = {}) => execFileSync('git', args, { cwd, encoding: 'utf8', env: { ...process.env, ...env }, stdio: ['ignore', 'pipe', 'pipe'] }).trim()
21
+
22
+ export function workTreeOf (dir) {
23
+ try {
24
+ return git(dir, ['rev-parse', '--show-toplevel'])
25
+ } catch (err) {
26
+ if (/not a git repository/.test(err.stderr ?? '')) return null
27
+ throw err
28
+ }
29
+ }
30
+
31
+ export function gitStateText (dir) {
32
+ const top = workTreeOf(dir)
33
+ if (!top) return 'not a git repository — nothing can be undone'
34
+ const changed = git(dir, ['status', '--porcelain', '--', '.']).split('\n').filter(Boolean).length
35
+ return changed ? `git: ${changed} file${changed > 1 ? 's' : ''} changed, a snapshot is taken each session` : 'git: clean, a snapshot is taken each session'
36
+ }
37
+
38
+ const withIndex = (fn) => {
39
+ const scratch = mkdtempSync(join(tmpdir(), 'spore-here-'))
40
+ try {
41
+ return fn({ GIT_INDEX_FILE: join(scratch, 'index') })
42
+ } finally {
43
+ rmSync(scratch, { recursive: true, force: true })
44
+ }
45
+ }
46
+
47
+ export function treeOf (dir) {
48
+ const top = workTreeOf(dir)
49
+ const scope = relative(top, dir) || '.'
50
+ return withIndex(index => {
51
+ git(top, ['add', '-A', '--', scope], index)
52
+ return git(top, ['write-tree'], index)
53
+ })
54
+ }
55
+
56
+ /** A commit of `dir` as it stands, kept under `refs/spore/<spore>/<session>`; its ref. */
57
+ export function snapshot (dir, { spore, session }) {
58
+ const top = workTreeOf(dir)
59
+ const commit = git(top, ['commit-tree', treeOf(dir), '-m', `spore ${spore}: session ${session}`], IDENTITY)
60
+ const ref = `refs/spore/${spore}/${session}`
61
+ git(top, ['update-ref', ref, commit])
62
+ return ref
63
+ }
64
+
65
+ /**
66
+ * Drops all but the newest `keep` of `spore`'s session snapshots, so what an old one holds — an
67
+ * untracked file since deleted — leaves `.git` with it; the refs dropped, oldest first. Session
68
+ * names are UTC times, so their order is their names'.
69
+ */
70
+ export function pruneSnapshots (dir, { spore, keep }) {
71
+ const top = workTreeOf(dir)
72
+ const refs = git(top, ['for-each-ref', '--sort=refname', '--format=%(refname)', `refs/spore/${spore}/`]).split('\n').filter(Boolean)
73
+ const dropped = refs.slice(0, Math.max(0, refs.length - keep))
74
+ for (const ref of dropped) git(top, ['update-ref', '-d', ref])
75
+ return dropped
76
+ }
77
+
78
+ /** What changed in `dir` since `ref`: `{ status, path }`, A added, M modified, D deleted. */
79
+ export function changesSince (dir, ref) {
80
+ const top = workTreeOf(dir)
81
+ const out = git(top, ['diff', '--no-renames', '--name-status', `${ref}^{tree}`, treeOf(dir)])
82
+ return out.split('\n').filter(Boolean).map(line => {
83
+ const [status, path] = line.split('\t')
84
+ return { status, path }
85
+ })
86
+ }
87
+
88
+ export function diffArgs (dir, ref) {
89
+ return { cwd: workTreeOf(dir), args: ['diff', `${ref}^{tree}`, treeOf(dir)] }
90
+ }
91
+
92
+ /** Puts `dir` back as it was at `ref`: what changed or went is restored, what was made is removed. */
93
+ export function undoTo (dir, ref) {
94
+ const top = workTreeOf(dir)
95
+ const changes = changesSince(dir, ref)
96
+ const restore = changes.filter(c => c.status !== 'A').map(c => c.path)
97
+ if (restore.length) {
98
+ withIndex(index => {
99
+ git(top, ['read-tree', `${ref}^{tree}`], index)
100
+ execFileSync('git', ['checkout-index', '-f', '--stdin'], { cwd: top, input: restore.join('\n') + '\n', env: { ...process.env, ...index }, stdio: ['pipe', 'pipe', 'pipe'] })
101
+ })
102
+ }
103
+ for (const { path } of changes.filter(c => c.status === 'A')) unlinkSync(join(top, path))
104
+ return changes
105
+ }
package/src/hooks.js ADDED
@@ -0,0 +1,89 @@
1
+ import { durationText, listHooks, showHook } from '@rhizogrip/spore'
2
+
3
+ import { createServices } from './services.js'
4
+
5
+ const JOURNAL_LINES = 20
6
+ const ANSWER_CHARS = 120
7
+ const UNAVAILABLE = new Set(['SERVICE_NO_SYSTEMD', 'SERVICE_NOT_DEFINED'])
8
+
9
+ const kb = (bytes) => bytes >= 1024 * 1024 ? `${(bytes / 1024 / 1024).toFixed(1)}MB` : `${Math.round(bytes / 1024)}KB`
10
+
11
+ const verifyText = ({ method, header }) => header ? `${method} on ${header}` : method
12
+
13
+ const acceptText = (accept) => [
14
+ accept.header ? `${accept.header} in ${accept.values.join(', ')}` : null,
15
+ accept.payload ? 'payload schema' : null
16
+ ].filter(Boolean).join(' · ')
17
+
18
+ const judgedBy = (spore) => [spore.router && 'router', spore.triage && 'triage'].filter(Boolean).join(' + ')
19
+
20
+ function sporeLine (spore, width) {
21
+ const head = `→ ${spore.name.padEnd(width)}`
22
+ if (!spore.ws) return `${head} no such spore`
23
+ return [
24
+ `${head} ${spore.count} delivered${spore.last ? `, last ${spore.last}` : ''}`,
25
+ spore.held.length ? `${spore.held.length} held` : null,
26
+ spore.accept ? `accepts ${acceptText(spore.accept)}` : null,
27
+ judgedBy(spore) || null
28
+ ].filter(Boolean).join(' · ')
29
+ }
30
+
31
+ function renderHooks ({ file, hooks }) {
32
+ if (!hooks.length) {
33
+ console.log(`${file} names no hook`)
34
+ return
35
+ }
36
+ console.log(`${file} — deliveries over the last 7 days\n`)
37
+ const width = Math.max(...hooks.map(hook => hook.name.length))
38
+ for (const hook of hooks) {
39
+ console.log(` ${hook.name.padEnd(width)} ${hook.path} · ${verifyText(hook.verify)}${hook.accept ? ` · accepts ${acceptText(hook.accept)}` : ''}`)
40
+ const sporeWidth = Math.max(...hook.spores.map(spore => spore.name.length))
41
+ for (const spore of hook.spores) console.log(` ${''.padEnd(width)} ${sporeLine(spore, sporeWidth)}`)
42
+ }
43
+ }
44
+
45
+ function renderHook (hook) {
46
+ console.log(`${hook.name} — ${hook.path}`)
47
+ console.log(` verify ${verifyText(hook.verify)}`)
48
+ if (hook.accept) console.log(` accepts ${acceptText(hook.accept)}`)
49
+ console.log(` bounds ${kb(hook.maxBytes)} a request · ${hook.perHour} turns an hour · ${hook.maxWait ? `waits up to ${durationText(hook.maxWait)} · ${hook.perDay} triage cells a day` : 'released at once'}`)
50
+ for (const spore of hook.spores) {
51
+ console.log(`\n${sporeLine(spore, spore.name.length)}`)
52
+ if (!spore.ws) continue
53
+ if (spore.router) console.log(` router ${spore.router}`)
54
+ if (spore.triage) console.log(` triage ${spore.triage}`)
55
+ for (const held of spore.held) console.log(` held since ${held.at}, released ${held.releaseAt}, at the latest ${held.deadline}${held.summary ? ` — ${held.summary}` : ''}`)
56
+ for (const d of spore.deliveries) {
57
+ const fate = d.turnNo ? `turn ${d.turnNo} ${d.stopReason ?? 'running'}` : d.consumed ? 'read' : 'waiting'
58
+ console.log(` ${d.at} ${[d.event, d.delivery].filter(Boolean).join(' ')} ${fate}`)
59
+ }
60
+ for (const cell of spore.cells) {
61
+ console.log(` triage ${cell.at} ${cell.ref ?? ''} ${cell.error ? `failed — ${cell.error}` : cell.answer.slice(0, ANSWER_CHARS)} $${cell.costUsd.toFixed(4)}`)
62
+ }
63
+ }
64
+ console.log(hook.journal === null ? `\nno journal: ${hook.journalWhy}` : `\n${hook.journal || 'the webhook service logged nothing about it'}`)
65
+ }
66
+
67
+ const journalOf = (services, name) => {
68
+ try {
69
+ const pattern = `^(hook ${name.replaceAll('.', '\\.')} |\\S+ /hook/${name.replaceAll('.', '\\.')}[/? ])`
70
+ return { journal: services.journal('webhook', { grep: pattern, lines: JOURNAL_LINES }), journalWhy: null }
71
+ } catch (err) {
72
+ if (!UNAVAILABLE.has(err.type)) throw err
73
+ return { journal: null, journalWhy: err.message }
74
+ }
75
+ }
76
+
77
+ export function hook (argv, emit, { services = createServices } = {}) {
78
+ const [, sub, name] = argv._.map(String)
79
+ if (!sub || sub === 'ls') return emit(listHooks(), renderHooks)
80
+ if (sub !== 'show') {
81
+ console.error(`spore: hook has no "${sub}" — ls, show`)
82
+ return 2
83
+ }
84
+ if (!name) {
85
+ console.error('spore: hook show needs a hook — spore hook show <hook>, from spore hook ls')
86
+ return 2
87
+ }
88
+ return emit({ ...showHook(name), ...journalOf(services(), name) }, renderHook)
89
+ }