nervur 0.1.0 → 0.2.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/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,53 @@
1
+ # nervur
2
+
3
+ The nervur CLI — the operator's command-line face over a running carcass.
4
+ It is a client, never the runtime: every verb speaks to the carcass's HTTP
5
+ API, and the same verbs exist at parity on the nervur console, the
6
+ machine-level face the carcass serves on loopback.
7
+
8
+ nervur is neutral ground for inter-company work: two companies are two
9
+ cryptographic identities meeting in one shared datastore that neither hosts
10
+ and both can read. Humans and AI agents are first-class colleagues on it.
11
+
12
+ ## Install
13
+
14
+ ```sh
15
+ npm create nervur
16
+ ```
17
+
18
+ One command stands the whole thing: verifies Docker (binary · daemon ·
19
+ permission, each failure a one-line fix), pulls the carcass image, lays down
20
+ compose + volume under `~/.nervur`, and mints your first identity.
21
+
22
+ ## Verbs
23
+
24
+ ```text
25
+ carcass family: install, up, down, reset, preflight, whoami, status,
26
+ identity, use, add, list, remove
27
+ being family: scaffold, deploy, species
28
+
29
+ install Docker preflight, then stand a carcass at
30
+ NERVUR_HOME (default ~/.nervur)
31
+ whoami · status the carcass answers with its identity and state
32
+ identity add <name> mint an identity on this machine (silent, idempotent);
33
+ --key <file> adopts a brought ed25519 key instead —
34
+ it never replaces an existing different owner
35
+ identity key <name> print the identity's private key (base64url PKCS8),
36
+ the exact shape --key accepts back
37
+ identity list identities on this machine · name + public id
38
+ identity remove <name> destroy an identity — refused while beings or
39
+ sealed lineages remain (only an empty one goes)
40
+ use [name] select which identity add/list act as
41
+ add <kind> [--as name] add a being under the selected identity
42
+ list · remove <name> the fleet registry · retire a being
43
+ scaffold <name> mint a species repo (the DNA)
44
+ deploy <name> <repo> <hash> grant + pin + run a species
45
+ species list deployed species and their pins
46
+ ```
47
+
48
+ No verb ever prompts — every fork is a flag or env var with a sane default,
49
+ and destructive turns are their own explicitly named verbs.
50
+
51
+ ## License
52
+
53
+ Apache-2.0 — see [LICENSE](./LICENSE).
package/completion.js ADDED
@@ -0,0 +1,122 @@
1
+ // nervur — shell completion (`nervur completion [bash|zsh]`). Client-local like
2
+ // scaffold: touches no carcass. One verb table is the single truth; both scripts
3
+ // are generated from it so a new verb lands in completion by editing one list.
4
+ // No prompt anywhere: the shell is a positional with a sane default ($SHELL).
5
+
6
+ import { appendFileSync, existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'
7
+ import { homedir } from 'node:os'
8
+ import { join } from 'node:path'
9
+
10
+ // verb → one-line description; subs/kinds drive second-position completion.
11
+ export const VERBS = [
12
+ ['install', 'stand a published carcass at NERVUR_HOME'],
13
+ ['up', '(dev bench) preflight, then stand the ground'],
14
+ ['down', 'stop the ground'],
15
+ ['reset', 'stop the ground and wipe its data'],
16
+ ['preflight', 'run the bench preflight and report'],
17
+ ['whoami', 'ask the carcass who it is'],
18
+ ['status', 'ask the carcass for its status'],
19
+ ['identity', 'manage identities (add · key · list · remove)'],
20
+ ['use', 'select the identity the verbs act as'],
21
+ ['add', 'add a being under the selected identity'],
22
+ ['list', 'list the beings on the ground'],
23
+ ['remove', 'remove a being'],
24
+ ['scaffold', 'mint a species repo from a template'],
25
+ ['deploy', 'grant + pin + run a species'],
26
+ ['species', 'list deployed species and their pins'],
27
+ ['completion', 'print the shell completion script (bash · zsh)'],
28
+ ['help', 'show help']
29
+ ]
30
+
31
+ const names = VERBS.map(([v]) => v).join(' ')
32
+
33
+ const bash = () => `# nervur completion (bash)
34
+ # load now: eval "$(nervur completion bash)"
35
+ # persist: nervur completion bash >> ~/.bashrc (or into bash_completion.d)
36
+ _nervur() {
37
+ local cur prev
38
+ cur="\${COMP_WORDS[COMP_CWORD]}"
39
+ prev="\${COMP_WORDS[COMP_CWORD-1]}"
40
+ case "$prev" in
41
+ identity) COMPREPLY=($(compgen -W "add key list remove" -- "$cur")); return ;;
42
+ completion) COMPREPLY=($(compgen -W "bash zsh" -- "$cur")); return ;;
43
+ add|--kind) COMPREPLY=($(compgen -W "empty" -- "$cur")); return ;;
44
+ --dir) COMPREPLY=($(compgen -d -- "$cur")); return ;;
45
+ esac
46
+ case "$cur" in
47
+ --*) COMPREPLY=($(compgen -W "--as --no-door --kind --dir --key" -- "$cur")); return ;;
48
+ esac
49
+ if [ "$COMP_CWORD" -eq 1 ]; then
50
+ COMPREPLY=($(compgen -W "${names}" -- "$cur"))
51
+ fi
52
+ }
53
+ complete -F _nervur nervur
54
+ `
55
+
56
+ const zsh = () => `#compdef nervur
57
+ # nervur completion (zsh)
58
+ # load now: eval "$(nervur completion zsh)"
59
+ # persist: nervur completion zsh > "\${fpath[1]}/_nervur" && rm -f ~/.zcompdump; compinit
60
+ _nervur() {
61
+ local -a verbs
62
+ verbs=(
63
+ ${VERBS.map(([v, d]) => ` '${v}:${d.replace(/'/g, "'\\''")}'`).join('\n')}
64
+ )
65
+ if (( CURRENT == 2 )); then
66
+ _describe 'verb' verbs
67
+ return
68
+ fi
69
+ case "\${words[2]}" in
70
+ identity) (( CURRENT == 3 )) && _values 'sub' add key list remove ;;
71
+ completion) (( CURRENT == 3 )) && _values 'shell' bash zsh ;;
72
+ add) (( CURRENT == 3 )) && _values 'kind' empty ;;
73
+ scaffold) _arguments '--kind[template kind]:kind:(empty)' '--dir[target directory]:dir:_directories' ;;
74
+ up|preflight) _arguments '--no-door[stand on localhost only (headless/CI)]' ;;
75
+ esac
76
+ }
77
+ if (( ! $+functions[compdef] )); then
78
+ autoload -Uz compinit
79
+ compinit
80
+ fi
81
+ compdef _nervur nervur
82
+ `
83
+
84
+ export function completionScript(shell) {
85
+ const which = shell ?? (process.env.SHELL?.endsWith('zsh') ? 'zsh' : 'bash')
86
+ if (which === 'zsh') return zsh()
87
+ if (which === 'bash') return bash()
88
+ throw new Error(`usage: nervur completion [bash|zsh] — '${which}' is not a shell I know`)
89
+ }
90
+
91
+ const MARK_OPEN = '# >>> nervur completion >>>'
92
+ const MARK_CLOSE = '# <<< nervur completion <<<'
93
+
94
+ // Wire completion for the operator's shell: the script lands as a file in the
95
+ // nervur home and the rc file gains one marked source-block — sourcing a file
96
+ // costs nothing per shell start, where `eval "$(nervur completion)"` would
97
+ // spawn node every time. Idempotent by the marker block (the dev/hosts.sh
98
+ // idiom): re-wiring rewrites the block in place, never stacks a second one.
99
+ export function wireCompletion(home) {
100
+ const shell = process.env.SHELL?.endsWith('zsh')
101
+ ? 'zsh'
102
+ : process.env.SHELL?.endsWith('bash')
103
+ ? 'bash'
104
+ : null
105
+ if (!shell) return { wired: false }
106
+ mkdirSync(home, { recursive: true })
107
+ const scriptPath = join(home, `completion.${shell}`)
108
+ writeFileSync(scriptPath, completionScript(shell))
109
+ const rc = join(homedir(), shell === 'zsh' ? '.zshrc' : '.bashrc')
110
+ const block = `${MARK_OPEN}\n[ -f "${scriptPath}" ] && source "${scriptPath}"\n${MARK_CLOSE}\n`
111
+ const current = existsSync(rc) ? readFileSync(rc, 'utf8') : ''
112
+ if (current.includes(MARK_OPEN)) {
113
+ const next = current.replace(
114
+ current.slice(current.indexOf(MARK_OPEN), current.indexOf(MARK_CLOSE) + MARK_CLOSE.length + 1),
115
+ block
116
+ )
117
+ if (next !== current) writeFileSync(rc, next)
118
+ } else {
119
+ appendFileSync(rc, `${current && !current.endsWith('\n') ? '\n' : ''}\n${block}`)
120
+ }
121
+ return { wired: true, shell, rc, scriptPath }
122
+ }
package/nervur.js CHANGED
@@ -6,6 +6,7 @@
6
6
  // LIVE ground, not a fresh in-process being.
7
7
 
8
8
  import { spawnSync } from 'node:child_process'
9
+ import { createHash } from 'node:crypto'
9
10
  import { existsSync, mkdirSync, readFileSync, realpathSync, rmSync, writeFileSync } from 'node:fs'
10
11
  import { homedir } from 'node:os'
11
12
  import { dirname, join } from 'node:path'
@@ -14,6 +15,8 @@ import { pathToFileURL } from 'node:url'
14
15
  import { resolveTemplate } from '@nervur-org/kit/templates.js'
15
16
  import { runPreflight, renderChain, blockingFailure } from './preflight.js'
16
17
  import { scaffoldSpecies } from './scaffold.js'
18
+ import { completionScript, wireCompletion, VERBS } from './completion.js'
19
+ import { banner, bold, columns, cyan, dim, heading, identityTree, red } from './style.js'
17
20
 
18
21
  // The one published tag — what `nervur install` pulls, and what a local
19
22
  // `docker build` must name for install to find it (papers/dev.md — "the
@@ -144,8 +147,11 @@ const postJsonStatus = async (url, body) => {
144
147
  // loopback via the NERVUR_PORT/NERVUR_FACES_PORT seams. Caddy fronting is parked
145
148
  // (papers/prod.md — "arrives with the per-box configuration"); this is the honest
146
149
  // floor today. Rewritten on every `install` — mechanical, never hand-edited.
147
- function installCompose() {
148
- return `name: nervur
150
+ // Docker derives volume/network names from the project name — a fixed name would
151
+ // share one state volume across every NERVUR_HOME on the machine.
152
+ function installCompose(home) {
153
+ const scope = createHash('sha256').update(realpathSync(home)).digest('hex').slice(0, 8)
154
+ return `name: nervur-${scope}
149
155
 
150
156
  # Generated by \`nervur install\` — the published carcass stand (papers/host.md,
151
157
  # papers/dev.md § the published install idiom). Image disposable, volume durable:
@@ -225,6 +231,7 @@ async function main() {
225
231
 
226
232
  const faceDomain = config.domains?.face
227
233
 
234
+ const bare = rawArgs.length === 0
228
235
  const [verb = 'whoami', ...args] = rawArgs
229
236
  const print = (v) => console.log(JSON.stringify(v, null, 2))
230
237
 
@@ -266,7 +273,7 @@ async function main() {
266
273
  console.log(renderChain(results))
267
274
  const blocked = blockingFailure(results)
268
275
  if (blocked) {
269
- console.error(`\n refusing: ${blocked.name} — ${blocked.note}\n fix: ${blocked.fix}`)
276
+ console.error(`\n ${red('refusing:')} ${blocked.name} — ${blocked.note}\n ${dim('fix:')} ${blocked.fix}`)
270
277
  process.exit(1)
271
278
  }
272
279
 
@@ -275,17 +282,16 @@ async function main() {
275
282
  const port = process.env.NERVUR_PORT ?? '4000'
276
283
  const facesPort = process.env.NERVUR_FACES_PORT ?? '4400'
277
284
 
278
- // The carcass image: present locally, or pullable. No registry is published
279
- // yet, so a pull will fail honestly — refuse with the exact local fix rather
280
- // than raising a compose against an image that isn't there.
285
+ // Refused here, before the compose — `compose up` against a missing image
286
+ // fails too, but far less legibly than this message.
281
287
  const inspect = spawnSync('docker', ['image', 'inspect', image], { stdio: 'ignore' })
282
288
  if (inspect.status !== 0) {
283
289
  console.log(` · image ${image} not found locally — trying \`docker pull\`…`)
284
290
  const pull = spawnSync('docker', ['pull', image], { stdio: 'inherit' })
285
291
  if (pull.status !== 0) {
286
292
  console.error(
287
- `\n refusing: no carcass image '${image}' locally, and no registry to pull from yet.\n` +
288
- ` fix: \`docker build -f carcass/Dockerfile -t ${image} .\` builds it, or \`docker pull ${image}\` once a registry is published`
293
+ `\n refusing: no carcass image '${image}' locally, and the pull failed.\n` +
294
+ ` fix: check the network and the image name — \`docker pull ${image}\` by hand shows the registry's answer; \`docker build -f carcass/Dockerfile -t ${image} .\` builds it locally`
289
295
  )
290
296
  process.exit(1)
291
297
  }
@@ -296,7 +302,7 @@ async function main() {
296
302
  // boot converges whatever it finds, papers/host.md).
297
303
  mkdirSync(home, { recursive: true })
298
304
  const composePath = join(home, 'compose.yml')
299
- writeFileSync(composePath, installCompose())
305
+ writeFileSync(composePath, installCompose(home))
300
306
  const groundPath = join(home, 'ground.config.js')
301
307
  if (!existsSync(groundPath)) writeFileSync(groundPath, installGroundConfig())
302
308
 
@@ -311,8 +317,26 @@ async function main() {
311
317
 
312
318
  const localUrl = `http://localhost:${port}`
313
319
  await knock({ localUrl: `${localUrl}/health` })
314
- console.log(` · carcass standing at ${home} — face on ${localUrl}`)
315
320
  print(await getJson(`${localUrl}/whoami`))
321
+
322
+ // TTY-gated: CI, probes, and scripts must never gain an rc edit as a
323
+ // side effect of install; NERVUR_COMPLETION=0 opts a human out too.
324
+ let completionRow = ['shell', 'nervur completion', 'prints the autocomplete script']
325
+ if (process.stdout.isTTY && process.env.NERVUR_COMPLETION !== '0') {
326
+ const wired = wireCompletion(home)
327
+ if (wired.wired)
328
+ completionRow = ['shell', `${wired.shell} autocomplete wired`, `${wired.rc} — new shells complete`]
329
+ }
330
+
331
+ const consolePort = process.env.NERVUR_CONSOLE_PORT ?? '4200'
332
+ console.log(
333
+ banner('nervur is standing', [
334
+ ['console', cyan(`http://localhost:${consolePort}`), 'open in your browser'],
335
+ ['home', home, 'compose + ground config, kept across installs'],
336
+ completionRow,
337
+ ['next', 'nervur add empty', 'stand your first being']
338
+ ]) + `\n ${dim(`api ${localUrl}`)}\n`
339
+ )
316
340
  break
317
341
  }
318
342
  case 'preflight': {
@@ -331,7 +355,7 @@ async function main() {
331
355
  console.log(renderChain(results))
332
356
  const blocked = blockingFailure(results)
333
357
  if (blocked) {
334
- console.error(`\n refusing: ${blocked.name} — ${blocked.note}\n fix: ${blocked.fix}`)
358
+ console.error(`\n ${red('refusing:')} ${blocked.name} — ${blocked.note}\n ${dim('fix:')} ${blocked.fix}`)
335
359
  process.exit(1)
336
360
  }
337
361
  if (config.certs) sh('bash', [config.certs])
@@ -355,6 +379,14 @@ async function main() {
355
379
  )
356
380
  print(await getJson(`${face()}/whoami`))
357
381
  }
382
+ // The console is loopback-only by design (host.md — "One operator, one
383
+ // console"), so its URL is localhost even when the face answers through
384
+ // the domain door.
385
+ console.log(
386
+ banner('ground is standing', [
387
+ ['console', cyan(`http://localhost:${config.console?.port ?? 4200}`), 'open in your browser']
388
+ ]) + `\n ${dim(`api ${via === 'domain' ? `https://${faceDomain}` : face()}`)}\n`
389
+ )
358
390
  break
359
391
  }
360
392
  case 'down':
@@ -366,9 +398,25 @@ async function main() {
366
398
  for (const dir of config.dataDirs ?? []) rmSync(dir, { recursive: true, force: true })
367
399
  console.log('reset')
368
400
  break
369
- case 'whoami':
370
- print(await getJson(`${face()}/whoami`))
401
+ case 'whoami': {
402
+ const who = await getJson(`${face()}/whoami`)
403
+ if (!bare || !process.stdout.isTTY) {
404
+ print(who)
405
+ break
406
+ }
407
+ const consoleUrl = `http://localhost:${process.env.NERVUR_CONSOLE_PORT ?? config.console?.port ?? 4200}`
408
+ const beings = who.beings ?? []
409
+ const tree = identityTree(who.identities ?? [], beings, selectedIdentity)
410
+ const hint = beings.length
411
+ ? ''
412
+ : `\n\n ${dim('nervur add empty stands your first being')}`
413
+ console.log(
414
+ `\n${heading(`nervur — carcass ${who.health} ${dim(`· v${who.version}`)}`)}\n\n${tree}${hint}\n\n` +
415
+ `${columns([['console', cyan(consoleUrl), 'open in your browser']])}\n\n` +
416
+ ` ${dim(`api ${face()} · faces ${who.faces ?? '—'}`)}\n`
417
+ )
371
418
  break
419
+ }
372
420
  case 'status':
373
421
  print(await getJson(`${face()}/status`))
374
422
  break
@@ -380,22 +428,48 @@ async function main() {
380
428
  })
381
429
  )
382
430
  break
383
- case 'list':
384
- print(await getJson(`${face()}/fleet/list`))
431
+ case 'list': {
432
+ const fleet = await getJson(`${face()}/fleet/list`)
433
+ if (!process.stdout.isTTY) {
434
+ print(fleet)
435
+ break
436
+ }
437
+ const identities = (await getJson(`${face()}/identities`)).map((i) => i.name)
438
+ console.log(`\n${identityTree(identities, fleet, selectedIdentity)}\n`)
385
439
  break
440
+ }
386
441
  case 'remove':
387
442
  if (!args[0]) throw new Error('usage: nervur remove <name>')
388
443
  print(await postJson(`${face()}/fleet/remove`, { name: args[0] }))
389
444
  break
390
445
  // ── identities (papers/host.md — "The identities"): locally one carcass
391
- // custodies many, one vault each. `add` mints silently, `list` shows the
392
- // public ids only, `remove` refuses (409) while any being is attached —
393
- // never force, never prompt.
446
+ // custodies many, one vault each. `add` mints silently — or adopts a brought
447
+ // key (`--key`, the bring-your-own-key seed; a different key never replaces
448
+ // an owner, 409). `list` shows the public ids only; `key` prints the owner's
449
+ // private key (the export half, hand-to-self); `remove` refuses (409) while
450
+ // any being is attached — never force, never prompt.
394
451
  case 'identity': {
395
452
  const [sub, name] = positional(args)
396
453
  if (sub === 'add') {
397
- if (!name) throw new Error('usage: nervur identity add <name>')
398
- print(await postJson(`${face()}/identities/add`, { name }))
454
+ if (!name) throw new Error('usage: nervur identity add <name> [--key <file>]')
455
+ const keyFile = flagValue(args, '--key')
456
+ const key = keyFile ? readFileSync(keyFile, 'utf8').trim() : undefined
457
+ const { status, body } = await postJsonStatus(`${face()}/identities/add`, { name, key })
458
+ if (status >= 400) {
459
+ console.error(`nervur: ${body.error}`)
460
+ process.exit(1)
461
+ }
462
+ print(body)
463
+ } else if (sub === 'key') {
464
+ if (!name) throw new Error('usage: nervur identity key <name>')
465
+ const { status, body } = await postJsonStatus(`${face()}/identities/key`, { name })
466
+ if (status >= 400) {
467
+ console.error(`nervur: ${body.error}`)
468
+ process.exit(1)
469
+ }
470
+ // The secret alone, pipe-friendly (`nervur identity key acme > key.txt`) —
471
+ // base64url PKCS8 DER, the exact shape `identity add --key` accepts back.
472
+ console.log(body.secret)
399
473
  } else if (sub === 'list') {
400
474
  const list = await getJson(`${face()}/identities`)
401
475
  for (const i of list)
@@ -404,10 +478,17 @@ async function main() {
404
478
  if (!name) throw new Error('usage: nervur identity remove <name>')
405
479
  const { status, body } = await postJsonStatus(`${face()}/identities/remove`, { name })
406
480
  if (status === 409) {
407
- console.error(
408
- `refused: identity '${name}' still has beings attached: ${body.beings.join(', ')}`
409
- )
410
- for (const b of body.beings) console.error(` fix: nervur remove ${b}`)
481
+ if (body.beings) {
482
+ console.error(
483
+ `refused: identity '${name}' still has beings attached: ${body.beings.join(', ')}`
484
+ )
485
+ for (const b of body.beings) console.error(` fix: nervur remove ${b}`)
486
+ } else {
487
+ console.error(
488
+ `refused: identity '${name}' still holds sealed lineages: ${body.lineages.join(', ')}`
489
+ )
490
+ console.error(' lineage destruction has no verb yet — the sealed custody stays')
491
+ }
411
492
  process.exit(1)
412
493
  }
413
494
  if (status >= 400) {
@@ -416,7 +497,7 @@ async function main() {
416
497
  }
417
498
  print(body)
418
499
  } else {
419
- throw new Error('usage: nervur identity <add|list|remove> <name>')
500
+ throw new Error('usage: nervur identity <add|key|list|remove> <name>')
420
501
  }
421
502
  break
422
503
  }
@@ -428,6 +509,26 @@ async function main() {
428
509
  console.log(selectedIdentity)
429
510
  break
430
511
  }
512
+ // Sticky selection is a client act, but it selects a real vault — an
513
+ // unknown name is refused against the live list here, never stored to
514
+ // fail later as a runtime surprise on some other verb.
515
+ let known
516
+ try {
517
+ known = (await getJson(`${face()}/identities`)).map((i) => i.name)
518
+ } catch {
519
+ console.error(
520
+ `nervur: ${red(`cannot verify identity '${name}'`)} — no carcass answering at ${face()}\n` +
521
+ ` ${dim('fix:')} stand it first — nervur up (bench) or nervur install (published)`
522
+ )
523
+ process.exit(1)
524
+ }
525
+ if (!known.includes(name)) {
526
+ console.error(
527
+ `nervur: ${red(`no identity '${name}'`)} on this carcass — have: ${known.join(' · ') || '(none)'}\n` +
528
+ ` ${dim('fix:')} nervur identity add ${name}`
529
+ )
530
+ process.exit(1)
531
+ }
431
532
  mkdirSync(dirname(stickyPath), { recursive: true })
432
533
  writeFileSync(stickyPath, name)
433
534
  console.log(`using identity '${name}'`)
@@ -462,34 +563,61 @@ async function main() {
462
563
  case 'species':
463
564
  print(await getJson(`${face()}/deploy/list`))
464
565
  break
566
+ case 'completion':
567
+ process.stdout.write(completionScript(positional(args)[0]))
568
+ break
465
569
  case 'help':
466
570
  case '--help':
467
- case '-h':
571
+ case '-h': {
572
+ // Help renders from the same VERBS table completion generates from — a
573
+ // verb missing here was never added to cli/completion.js.
574
+ const sig = {
575
+ up: '[--no-door]',
576
+ preflight: '[--no-door]',
577
+ identity: '<add|key|list|remove> [name] [--key <file>]',
578
+ use: '[name]',
579
+ add: '<kind> [--as <identity>]',
580
+ remove: '<name>',
581
+ scaffold: '<name> [--kind empty] [--dir <path>]',
582
+ deploy: '<name> <repo> <full-commit-hash>',
583
+ completion: '[bash|zsh]'
584
+ }
585
+ const carcass = new Set([
586
+ 'install', 'up', 'down', 'reset', 'preflight', 'whoami', 'status',
587
+ 'identity', 'use', 'add', 'list', 'remove'
588
+ ])
589
+ // Pad on the UNSTYLED signature so ANSI codes never skew the column.
590
+ const width = Math.max(...VERBS.map(([v]) => `${v} ${sig[v] ?? ''}`.trim().length))
591
+ const row = ([v, d]) => {
592
+ const plain = `${v}${sig[v] ? ` ${sig[v]}` : ''}`
593
+ const left = `${bold(v)}${sig[v] ? ` ${dim(sig[v])}` : ''}`
594
+ return ` ${left}${' '.repeat(width - plain.length + 2)}${d}`
595
+ }
468
596
  console.log(
469
- 'nervur — client of a running carcass\n\n' +
470
- 'carcass family: install, up, down, reset, preflight, whoami, status, identity, use, add, list, remove\n' +
471
- 'being family: scaffold, deploy, species\n\n' +
472
- ' install Docker preflight, then stand a carcass at NERVUR_HOME (default ~/.nervur)\n' +
473
- ' [NERVUR_HOME, NERVUR_IMAGE, NERVUR_PORT, NERVUR_FACES_PORT]\n' +
474
- ' up [--no-door] (dev bench) run the bench preflight, then stand the ground\n' +
475
- ' preflight [--no-door] run the bench preflight and report (exit code = verdict)\n' +
476
- ' identity add <name> mint an identity on this machine (silent, idempotent)\n' +
477
- ' identity list list identities on this machine · name + public id\n' +
478
- ' identity remove <name> destroy an identity — refused (409) while beings remain\n' +
479
- ' use [name] select which identity add/list act as (client-only); no args prints it\n' +
480
- ' add <kind> [--as name] add a being under the selected (or --as) identity\n' +
481
- ' scaffold <name> mint a species repo (the DNA) [--kind empty] [--dir <path>]\n' +
482
- ' deploy <name> <repo> <full-commit-hash> grant + pin + run a species\n' +
483
- ' species list the deployed species and their pins\n\n' +
484
- 'the door is open by default; --no-door (or NERVUR_DOOR=0) stands the ground\n' +
485
- 'on localhost only for headless/CI — the hosts check degrades, 443 is skipped'
597
+ `${bold('nervur')} — client of a running carcass\n\n` +
598
+ `${dim('usage')} nervur <verb> [args] ${dim('[--as <identity>]')}\n\n` +
599
+ `${cyan('carcass family')}\n` +
600
+ VERBS.filter(([v]) => carcass.has(v)).map(row).join('\n') +
601
+ `\n\n${cyan('being family')}\n` +
602
+ VERBS.filter(([v]) => !carcass.has(v) && v !== 'help').map(row).join('\n') +
603
+ `\n\n${dim(
604
+ 'install honors NERVUR_HOME · NERVUR_IMAGE · NERVUR_PORT · NERVUR_FACES_PORT · NERVUR_CONSOLE_PORT\n' +
605
+ 'the door is open by default; --no-door (or NERVUR_DOOR=0) stands the ground\n' +
606
+ 'on localhost only for headless/CI — the hosts check degrades, 443 is skipped'
607
+ )}`
486
608
  )
487
609
  break
488
- default:
610
+ }
611
+ default: {
612
+ const known = VERBS.map(([v]) => v)
613
+ const near = known.filter((v) => v.startsWith(verb) || verb.startsWith(v.slice(0, 3)))
489
614
  console.error(
490
- `nervur: unknown verb: ${verb} (have: install, up, down, reset, preflight, whoami, status, identity, use, add, list, remove, scaffold, deploy, species)`
615
+ `nervur: ${red(`unknown verb: ${verb}`)}` +
616
+ (near.length ? ` — did you mean ${near.map(bold).join(' · ')}?` : '') +
617
+ `\n${dim(`have: ${known.join(', ')}`)}`
491
618
  )
492
619
  process.exit(1)
620
+ }
493
621
  }
494
622
  process.exit(0)
495
623
  }
@@ -508,7 +636,7 @@ function invokedAsCli() {
508
636
  }
509
637
  if (invokedAsCli()) {
510
638
  main().catch((e) => {
511
- console.error(`nervur: ${e.message}`)
639
+ console.error(`nervur: ${red(e.message)}`)
512
640
  process.exit(1)
513
641
  })
514
642
  }
package/package.json CHANGED
@@ -1,18 +1,20 @@
1
1
  {
2
2
  "name": "nervur",
3
- "version": "0.1.0",
3
+ "version": "0.2.0",
4
4
  "description": "The nervur CLI — a client of a running carcass, never the runtime (papers/host.md).",
5
5
  "type": "module",
6
6
  "bin": {
7
- "nervur": "./nervur.js"
7
+ "nervur": "nervur.js"
8
8
  },
9
9
  "files": [
10
10
  "nervur.js",
11
11
  "preflight.js",
12
- "scaffold.js"
12
+ "scaffold.js",
13
+ "completion.js",
14
+ "style.js"
13
15
  ],
14
16
  "dependencies": {
15
- "@nervur-org/kit": "*"
17
+ "@nervur-org/kit": "^0.1.0"
16
18
  },
17
19
  "license": "Apache-2.0"
18
20
  }
package/preflight.js CHANGED
@@ -14,6 +14,7 @@ import { spawnSync } from 'node:child_process'
14
14
  import { existsSync } from 'node:fs'
15
15
  import { dirname, join } from 'node:path'
16
16
  import { lookup } from 'node:dns/promises'
17
+ import { dim, glyph } from './style.js'
17
18
 
18
19
  // Status vocabulary: 'ok' passes; 'fail' blocks (refuse at the door); 'warn' is
19
20
  // advisory — a real finding that never blocks (browser trust, the door-closed
@@ -146,13 +147,13 @@ export async function runPreflight(config, { door = true } = {}) {
146
147
  ]
147
148
  }
148
149
 
149
- const GLYPH = { ok: '✓', fail: '✗', warn: '!', skip: '·' }
150
-
151
150
  export function renderChain(results) {
152
151
  const lines = []
153
152
  for (const r of results) {
154
- lines.push(` ${GLYPH[r.status] ?? '·'} ${r.name.padEnd(9)} ${r.note}`)
155
- if ((r.status === 'fail' || r.status === 'warn') && r.fix) lines.push(` ↳ fix: ${r.fix}`)
153
+ const note = r.status === 'skip' ? dim(r.note) : r.note
154
+ lines.push(` ${glyph[r.status] ?? glyph.skip} ${r.name.padEnd(9)} ${note}`)
155
+ if ((r.status === 'fail' || r.status === 'warn') && r.fix)
156
+ lines.push(` ${dim('↳ fix:')} ${r.fix}`)
156
157
  }
157
158
  return lines.join('\n')
158
159
  }
package/style.js ADDED
@@ -0,0 +1,82 @@
1
+ // nervur — CLI presentation: color and the standing banner. Pure node:util
2
+ // styleText, zero dependencies; color only when stdout is a TTY and NO_COLOR is
3
+ // unset, so piped output (probes, scripts) stays plain and machine-stable.
4
+
5
+ import * as util from 'node:util'
6
+
7
+ // util.styleText arrives in node 20.12/21.7 — a named import would crash the
8
+ // whole CLI on anything older (an operator's nvm default may lag), so ink is
9
+ // feature-detected: absent, everything renders plain instead of dying.
10
+ const styleText = util.styleText ?? ((_format, text) => text)
11
+ const stripVTControlCharacters = util.stripVTControlCharacters ?? ((s) => s)
12
+
13
+ const on = () => process.stdout.isTTY && !process.env.NO_COLOR
14
+
15
+ // paint(format, text) — styleText that degrades to plain text off-TTY. `format`
16
+ // is a styleText format or array of formats ('green', ['bold','cyan'], …).
17
+ export const paint = (format, text) => (on() ? styleText(format, text) : text)
18
+
19
+ export const dim = (t) => paint('dim', t)
20
+ export const bold = (t) => paint('bold', t)
21
+ export const red = (t) => paint('red', t)
22
+ export const green = (t) => paint('green', t)
23
+ export const yellow = (t) => paint('yellow', t)
24
+ export const cyan = (t) => paint('cyan', t)
25
+
26
+ // The status glyphs the preflight chain and the probes share, colored: the
27
+ // vocabulary stays ✓ ✗ ! · (preflight.js), only the ink changes.
28
+ export const glyph = {
29
+ ok: green('✓'),
30
+ fail: red('✗'),
31
+ warn: yellow('!'),
32
+ skip: dim('·')
33
+ }
34
+
35
+ // The standing banner — printed once the carcass answers, on `install` and `up`.
36
+ // The console line leads: it is the operator's browser door (host.md — "One
37
+ // operator, one console"), and the one URL a fresh operator should open first.
38
+ // rows: [label, value, note?]; labels and notes align in columns, notes ride
39
+ // dim. Values may carry ANSI ink, so columns measure the stripped length.
40
+ const plainLength = (s) => stripVTControlCharacters(s).length
41
+
42
+ export function columns(rows) {
43
+ const labelW = Math.max(...rows.map(([label]) => label.length))
44
+ const valueW = Math.max(...rows.map(([, value]) => plainLength(value)))
45
+ return rows
46
+ .map(([label, value, note]) => {
47
+ const pad = ' '.repeat(valueW - plainLength(value))
48
+ const noteStr = note ? `${pad} ${dim(note)}` : ''
49
+ return ` ${dim(label.padEnd(labelW))} ${value}${noteStr}`
50
+ })
51
+ .join('\n')
52
+ }
53
+
54
+ export const heading = (title) => ` ${paint(['bold', 'cyan'], '◆')} ${bold(title)}`
55
+
56
+ export function banner(title, rows) {
57
+ return `\n${heading(title)}\n\n${columns(rows)}\n`
58
+ }
59
+
60
+ // The identity → beings tree — the ground's real shape (beings live under
61
+ // identities, never flat). `identities` may lag `beings` (a being can outlive
62
+ // its vault's listing), so the tree is keyed by the union of both.
63
+ export function identityTree(identities, beings, selected) {
64
+ const byId = new Map(identities.map((i) => [i, []]))
65
+ for (const b of beings) {
66
+ if (!byId.has(b.identity)) byId.set(b.identity, [])
67
+ byId.get(b.identity).push(b)
68
+ }
69
+ const nameW = Math.max(0, ...beings.map((b) => b.name.length))
70
+ const lines = []
71
+ for (const [id, bs] of byId) {
72
+ const marks = [
73
+ id === selected ? cyan(' ← selected') : '',
74
+ identities.includes(id) ? '' : dim(' (no vault)')
75
+ ].join('')
76
+ lines.push(` ${bold(id)}${marks}`)
77
+ if (!bs.length) lines.push(dim(' · no beings'))
78
+ for (const b of bs)
79
+ lines.push(` ${b.name.padEnd(nameW)} ${dim(`${b.kind} · ${b.state}`)}`)
80
+ }
81
+ return lines.join('\n')
82
+ }