@future-unknown/known 0.0.0-stage → 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/lib/output.js ADDED
@@ -0,0 +1,338 @@
1
+ /**
2
+ * Terminal output — the single vocabulary every command renders through.
3
+ *
4
+ * This module owns the output primitives: the --json toggle, framing, color
5
+ * palette, and the shapes below. Nothing should reach for console.table or
6
+ * hand-roll its own column padding — route it through here so the whole CLI
7
+ * looks like one program.
8
+ *
9
+ * The shapes:
10
+ * table(rows, {columns}) a borderless, aligned grid (lists)
11
+ * cards(items, {heading, footer}) a list of entities that carry prose
12
+ * record(pairs) a key/value card (one entity's details)
13
+ * commands(rows) an aligned command list (menus + help)
14
+ * status(verb, subject, detail) a one-line result of a mutation
15
+ * empty(msg) a uniform "nothing here" line
16
+ *
17
+ * Every shape is --json aware: in --json mode the structural shapes print
18
+ * nothing and the command emits the raw record(s) via `data()` instead, so
19
+ * scripts get clean machine output and humans get the framed view.
20
+ */
21
+ require("@colors/colors")
22
+ const columnify = require("columnify")
23
+ const timeAgo = require("time_ago_in_words")
24
+
25
+ // Flipped on by bin/known when --json is present.
26
+ let jsonMode = false
27
+ function setJson(on) { jsonMode = !!on }
28
+ function isJson() { return jsonMode }
29
+
30
+ // Blank line above/below for breathing room, matching the house style.
31
+ function pad(fn) {
32
+ console.log()
33
+ fn()
34
+ console.log()
35
+ }
36
+
37
+ // Indent every line of a block by n spaces (columnify emits flush-left).
38
+ function indent(text, n) {
39
+ const lead = " ".repeat(n)
40
+ return text.split("\n").map((l) => (l ? lead + l : l)).join("\n")
41
+ }
42
+
43
+ // ---- the four shapes -------------------------------------------------------
44
+
45
+ // A borderless, aligned grid. `columns` fixes the order; headings are greyed,
46
+ // uppercased, and underscores become spaces ("created_by" → "CREATED BY").
47
+ // Cells may carry color — width is measured at visible length, so alignment
48
+ // holds. Empty lists are the caller's job (use `empty`).
49
+ function table(rows, opts) {
50
+ if (jsonMode) return data(rows)
51
+ const options = opts || {}
52
+ const text = columnify(rows, {
53
+ columns: options.columns,
54
+ columnSplitter: " ",
55
+ headingTransform: (h) => h.replace(/_/g, " ").toUpperCase().grey,
56
+ config: options.config || {}
57
+ })
58
+ pad(() => console.log(indent(text, 2)))
59
+ }
60
+
61
+ // A list of entities whose rows carry prose a grid would cut to nothing:
62
+ // one box each, fitted to the terminal. The title and an aside sit in the
63
+ // top border; the body is wrapped inside; a divider sets it off from the
64
+ // labelled fields below, one per line, a list value one item per line (an
65
+ // item starting with spaces sits under the one before it). Borders are grey
66
+ // so the content leads. An optional heading opens the list and a footer (a
67
+ // line, or several) closes it, in grey.
68
+ //
69
+ // ╭─ title ───────────────────────── aside ─╮
70
+ // │ body, wrapped │
71
+ // ├─────────────────────────────────────────┤
72
+ // │ label value │
73
+ // ╰─────────────────────────────────────────╯
74
+ //
75
+ // cards([{ title, aside, body, muted, fields: [[label, value | [values]]] }],
76
+ // { heading, footer })
77
+ //
78
+ // `muted` greys the body (a stand-in, not the real thing); a field whose
79
+ // value is empty shows an em dash, so every box has the same rows; a null
80
+ // in place of a field draws a divider, to group the rows. Width
81
+ // follows the terminal between CARD_MIN and CARD_MAX columns, so a wide
82
+ // screen keeps a readable measure and a narrow one still fits.
83
+ const CARD_MIN = 60
84
+ const CARD_MAX = 88
85
+ const CARD_DEFAULT = 80
86
+ const CARD_INDENT = 2
87
+ const CARD_LABEL_GAP = 3
88
+ const BOX = { tl: "╭", tr: "╮", bl: "╰", br: "╯", h: "─", v: "│", lt: "├", rt: "┤" }
89
+
90
+ function cards(items, opts) {
91
+ if (jsonMode) return data(items)
92
+ const options = opts || {}
93
+ const columns = process.stdout.columns || CARD_DEFAULT
94
+ const outer = Math.max(CARD_MIN, Math.min(CARD_MAX, columns)) - CARD_INDENT * 2
95
+ const inner = outer - 4
96
+ const lead = " ".repeat(CARD_INDENT)
97
+ const edge = (text) => text.grey
98
+ const row = (text) => edge(BOX.v) + " " + text + " ".repeat(Math.max(inner - visible(text), 0)) + " " + edge(BOX.v)
99
+ const rule = (left, right) => edge(left + BOX.h.repeat(outer - 2) + right)
100
+ const labelWidth = items.reduce((w, item) => (item.fields || []).filter(Boolean).reduce((m, [label]) => Math.max(m, label.length), w), 0)
101
+ const valueAt = labelWidth + CARD_LABEL_GAP
102
+ const boxes = items.map((item) => {
103
+ const lines = []
104
+ // ╭─ title ──── aside ─╮
105
+ const aside = item.aside ? String(item.aside) : ""
106
+ // corners (2), "─ " before the title, " " after it, and " aside ─" or "─"
107
+ const fill = outer - 2 - (2 + visible(item.title) + 1) - (aside ? 1 + visible(aside) + 2 : 1)
108
+ lines.push(edge(BOX.tl + BOX.h + " ") + item.title + " " + edge(BOX.h.repeat(Math.max(fill, 1))) + (aside ? " " + aside + edge(" " + BOX.h) : edge(BOX.h)) + edge(BOX.tr))
109
+ if (item.body) {
110
+ for (const line of wrap(item.body, inner)) lines.push(row(item.muted ? line.grey : line))
111
+ }
112
+ const fields = item.fields || []
113
+ if (fields.length) {
114
+ if (item.body) lines.push(rule(BOX.lt, BOX.rt))
115
+ for (const field of fields) {
116
+ if (field === null) {
117
+ lines.push(rule(BOX.lt, BOX.rt))
118
+ continue
119
+ }
120
+ const [label, value] = field
121
+ const values = [].concat(value === null || value === undefined ? [] : value).filter((v) => v !== null && v !== undefined && v !== "")
122
+ const shown = values.length ? values : ["—".grey]
123
+ shown.forEach((text, i) => {
124
+ const head = i === 0 ? label.grey + " ".repeat(labelWidth - label.length + CARD_LABEL_GAP) : " ".repeat(valueAt)
125
+ for (const [j, line] of fit(String(text), inner - valueAt).entries()) lines.push(row((j === 0 ? head : " ".repeat(valueAt)) + line))
126
+ })
127
+ }
128
+ }
129
+ lines.push(rule(BOX.bl, BOX.br))
130
+ return lines.map((line) => lead + line).join("\n")
131
+ })
132
+ pad(() => {
133
+ if (options.heading) console.log(lead + String(options.heading) + "\n")
134
+ console.log(boxes.join("\n\n"))
135
+ if (options.footer) {
136
+ console.log()
137
+ for (const text of [].concat(options.footer).filter(Boolean)) {
138
+ for (const line of wrap(text, outer)) console.log(lead + line.grey)
139
+ }
140
+ }
141
+ })
142
+ }
143
+
144
+ // A field value's lines: as it is when it fits or carries color (color is
145
+ // the caller's), else wrapped, keeping any leading indent on every line.
146
+ function fit(text, width) {
147
+ if (visible(text) <= width || visible(text) !== text.length) return [text]
148
+ const indentation = text.match(/^ */)[0]
149
+ return wrap(text, width - indentation.length).map((line) => indentation + line)
150
+ }
151
+
152
+ // Visible length of a string that may carry color codes.
153
+ function visible(text) {
154
+ return require("@colors/colors").strip(String(text)).length
155
+ }
156
+
157
+ // Words wrapped to `width` columns; past `max` lines the last one ends in an
158
+ // ellipsis. Plain text in, plain lines out (color is the caller's, per line).
159
+ function wrap(text, width, max) {
160
+ const words = String(text).replace(/\s+/g, " ").trim().split(" ")
161
+ const lines = []
162
+ let line = ""
163
+ for (const word of words) {
164
+ if (line && (line + " " + word).length > width) {
165
+ lines.push(line)
166
+ line = word
167
+ } else {
168
+ line = line ? line + " " + word : word
169
+ }
170
+ // a single word longer than the line is cut where it must be
171
+ while (line.length > width) {
172
+ lines.push(line.slice(0, width))
173
+ line = line.slice(width)
174
+ }
175
+ }
176
+ if (line) lines.push(line)
177
+ if (!max || lines.length <= max) return lines
178
+ const kept = lines.slice(0, max)
179
+ const last = kept[max - 1]
180
+ kept[max - 1] = (last.length >= width ? last.slice(0, width - 1) : last).replace(/[\s,;:.—-]+$/, "") + "…"
181
+ return kept
182
+ }
183
+
184
+ // A key/value card for a single entity. `pairs` is [[label, value], …]; the
185
+ // label column auto-sizes to the longest label. A null/blank value renders as
186
+ // an em dash so cards stay rectangular.
187
+ function record(pairs) {
188
+ if (jsonMode) return
189
+ const width = pairs.reduce((w, p) => Math.max(w, p[0].length), 0) + 3
190
+ pad(() => {
191
+ for (const [label, value] of pairs) {
192
+ const gap = " ".repeat(width - label.length)
193
+ const shown = value === null || value === undefined || value === "" ? "—".grey : String(value)
194
+ console.log(" " + label.grey + gap + shown)
195
+ }
196
+ })
197
+ }
198
+
199
+ // An aligned command list for menus and `known help`. `rows` is
200
+ // [[invocation, description], …]; the invocation keeps the terminal's default
201
+ // foreground (so it stays legible on light *and* dark backgrounds) and only the
202
+ // description is dimmed to grey — surge-style, subtle, no accent color.
203
+ // Borderless and headerless. The description column sits three spaces past the
204
+ // widest invocation. Pass `minWidth` to align several lists to a shared column
205
+ // (e.g. `known help`, whose sections must line up with each other); omit it and
206
+ // each list auto-fits its own contents (the contextual menus).
207
+ function commands(rows, minWidth) {
208
+ const width = rows.reduce((w, [cmd]) => Math.max(w, cmd.length), minWidth || 0)
209
+ const lines = rows.map(([cmd, desc]) => {
210
+ const gap = " ".repeat(width - cmd.length + 3)
211
+ return cmd + gap + (desc || "").grey
212
+ })
213
+ console.log(indent(lines.join("\n"), 3))
214
+ }
215
+
216
+ // The shared command-column width for a set of command lists: the longest
217
+ // invocation across all of them. Feed the result to `commands(rows, width)` so
218
+ // independent lists align to the same column.
219
+ function commandWidth(...rowGroups) {
220
+ return rowGroups.reduce(
221
+ (w, rows) => rows.reduce((m, [cmd]) => Math.max(m, cmd.length), w),
222
+ 0
223
+ )
224
+ }
225
+
226
+ // The one-line result of a mutation: "<verb> <subject> <detail>". Tone colors
227
+ // the verb — green for create/grant, red for destroy, grey for no-ops. JSON
228
+ // callers emit the raw result via `data()` instead and never reach here.
229
+ function status(verb, subject, detail, tone) {
230
+ if (jsonMode) return
231
+ const paint = tone === "danger" ? "red" : tone === "muted" ? "grey" : "green"
232
+ let line = " " + verb[paint]
233
+ if (subject) line += " " + String(subject).cyan
234
+ if (detail) line += (" " + detail).grey
235
+ pad(() => console.log(line))
236
+ }
237
+
238
+ // A uniform empty state, e.g. "no orgs".
239
+ function empty(msg) {
240
+ if (jsonMode) return
241
+ pad(() => console.log(" " + String(msg).grey))
242
+ }
243
+
244
+ // ---- machine output + framing ----------------------------------------------
245
+
246
+ // Primary success output. In --json mode, print machine-readable JSON only.
247
+ // In human mode it's a thin fallback for shapeless results (the escape-hatch
248
+ // `rpc`/`ping` paths); resource commands use the shapes above.
249
+ function data(value) {
250
+ if (jsonMode) {
251
+ process.stdout.write(JSON.stringify(value, null, 2) + "\n")
252
+ return
253
+ }
254
+ if (value === null || value === undefined) {
255
+ pad(() => console.log(" done".grey))
256
+ } else if (Array.isArray(value)) {
257
+ if (value.length) table(value)
258
+ else empty("(empty)")
259
+ } else if (typeof value === "object") {
260
+ record(Object.entries(value).map(([k, v]) => [k, formatScalar(v)]))
261
+ } else {
262
+ pad(() => console.log(" " + String(value)))
263
+ }
264
+ }
265
+
266
+ // Render a scalar for a record cell; objects/arrays fall back to compact JSON.
267
+ function formatScalar(v) {
268
+ if (v === null || v === undefined) return "—"
269
+ if (typeof v === "object") return JSON.stringify(v)
270
+ return String(v)
271
+ }
272
+
273
+ function info(msg) {
274
+ if (jsonMode) return
275
+ pad(() => console.log(" " + msg))
276
+ }
277
+
278
+ // A verbatim payload — page content, file bodies — printed exactly as stored so
279
+ // it composes with pipes and redirects: no framing, no indent, no color. A
280
+ // trailing newline is added only when the payload doesn't end with one. JSON
281
+ // callers emit via data() instead and never reach here.
282
+ function raw(text) {
283
+ if (jsonMode) return
284
+ const value = text === null || text === undefined ? "" : String(text)
285
+ process.stdout.write(value)
286
+ if (value && !value.endsWith("\n")) process.stdout.write("\n")
287
+ }
288
+
289
+ // Normalize a thrown value into {code,message,fields}. Two shapes reach here
290
+ // under the result model: a re-thrown refusal (carries `.fields`, a per-field
291
+ // map) and a MethodryError (carries a `.code` like "network"/"server"/
292
+ // "unauthorized"). Plain Errors and strings degrade gracefully.
293
+ function normalizeError(err) {
294
+ if (!err) return { message: "unknown error" }
295
+ if (typeof err === "string") return { message: err }
296
+ return {
297
+ code: err.code,
298
+ message: err.message || "unknown error",
299
+ fields: err.fields || null
300
+ }
301
+ }
302
+
303
+ function error(err) {
304
+ const e = normalizeError(err)
305
+ if (jsonMode) {
306
+ process.stdout.write(JSON.stringify({ error: e }, null, 2) + "\n")
307
+ return
308
+ }
309
+ pad(() => {
310
+ console.log(" " + "Error".red + " " + ("- " + e.message).grey)
311
+ if (e.fields && typeof e.fields === "object") {
312
+ for (const [field, msg] of Object.entries(e.fields)) {
313
+ console.log(" •".grey, (field + ": " + msg).grey)
314
+ }
315
+ }
316
+ })
317
+ }
318
+
319
+ module.exports = {
320
+ colors: require("@colors/colors"),
321
+ timeAgo,
322
+ setJson,
323
+ isJson,
324
+ pad,
325
+ indent,
326
+ table,
327
+ cards,
328
+ record,
329
+ commands,
330
+ commandWidth,
331
+ status,
332
+ empty,
333
+ data,
334
+ raw,
335
+ info,
336
+ error,
337
+ normalizeError
338
+ }
package/lib/project.js ADDED
@@ -0,0 +1,100 @@
1
+ /**
2
+ * Project binding: which org a directory belongs to.
3
+ *
4
+ * A `KNOWN_ORG` file names the org for everything beneath it — one line, the same
5
+ * reference `known <org> …` takes:
6
+ *
7
+ * acme
8
+ * acme@staging
9
+ *
10
+ * The nearest one wins, found by walking up from the working directory, so a
11
+ * file in a repo binds that repo and one in a parent folder binds every repo
12
+ * under it. It holds no secrets and is meant to be committed. `KNOWN_ORG` in
13
+ * the environment outranks any file — the file is named after the variable it
14
+ * stands in for. (Not `KNOWN`: macOS folds case, so it couldn't sit beside a
15
+ * `known/` directory.)
16
+ *
17
+ * A binding only *selects* a session that already exists. It never signs in and
18
+ * never falls back to another org: if the named session isn't on this machine,
19
+ * the command stops and says which sign-in to make.
20
+ */
21
+ const fs = require("fs")
22
+ const path = require("path")
23
+ const os = require("os")
24
+
25
+ const FILE = "KNOWN_ORG"
26
+ const ENV_VAR = "KNOWN_ORG"
27
+
28
+ // `<org>[@<env>]` — an org slug or id, optionally pinned to an environment
29
+ // (an alias or a host[:port]).
30
+ const REF = /^[A-Za-z0-9_-]+(@[A-Za-z0-9.:-]+)?$/
31
+
32
+ function friendly(message) {
33
+ const e = new Error(message)
34
+ e.friendly = true
35
+ return e
36
+ }
37
+
38
+ // Home-relative, for display.
39
+ function shortPath(file) {
40
+ const home = os.homedir()
41
+ return file === home || file.startsWith(home + path.sep) ? "~" + file.slice(home.length) : file
42
+ }
43
+
44
+ // The nearest `KNOWN_ORG` file at or above `dir`, or null. The name is matched
45
+ // exactly from a directory listing rather than stat'd, because macOS folds case
46
+ // and a stat would also hit a `known_org` of any spelling.
47
+ function findFile(dir) {
48
+ let current = path.resolve(dir)
49
+ while (true) {
50
+ let names = []
51
+ try { names = fs.readdirSync(current) } catch (e) {}
52
+ if (names.includes(FILE)) {
53
+ const file = path.join(current, FILE)
54
+ try {
55
+ if (fs.statSync(file).isFile()) return file
56
+ } catch (e) {}
57
+ }
58
+ const parent = path.dirname(current)
59
+ if (parent === current) return null
60
+ current = parent
61
+ }
62
+ }
63
+
64
+ // The org reference a `KNOWN_ORG` file holds: its one line, ignoring blank lines
65
+ // and `#` comments. Anything else is an error rather than a guess.
66
+ function parse(text, where) {
67
+ const lines = String(text)
68
+ .split(/\r?\n/)
69
+ .map((l) => l.trim())
70
+ .filter((l) => l && !l.startsWith("#"))
71
+ if (!lines.length) throw friendly(where + " is empty — write the org it belongs to, e.g. `acme`")
72
+ if (lines.length > 1) throw friendly(where + " should hold one org, found " + lines.length + " lines")
73
+ if (!REF.test(lines[0])) throw friendly(where + " holds “" + lines[0] + "” — expected an org like `acme` or `acme@staging`")
74
+ return lines[0]
75
+ }
76
+
77
+ /**
78
+ * The binding in effect for `dir` (default: the working directory), or null.
79
+ *
80
+ * { ref: "acme@staging", from: "~/work/acme/KNOWN_ORG", file: "/Users/…/KNOWN_ORG" }
81
+ * { ref: "acme", from: "$KNOWN_ORG" }
82
+ */
83
+ function binding(dir = process.cwd(), env = process.env) {
84
+ const fromEnv = env[ENV_VAR]
85
+ if (fromEnv !== undefined && String(fromEnv).trim() !== "") {
86
+ return { ref: parse(fromEnv, "$" + ENV_VAR), from: "$" + ENV_VAR }
87
+ }
88
+
89
+ const file = findFile(dir)
90
+ if (!file) return null
91
+ let text
92
+ try {
93
+ text = fs.readFileSync(file, "utf8")
94
+ } catch (e) {
95
+ throw friendly("can't read " + shortPath(file) + ": " + e.message)
96
+ }
97
+ return { ref: parse(text, shortPath(file)), from: shortPath(file), file }
98
+ }
99
+
100
+ module.exports = { FILE, ENV_VAR, binding, findFile, parse }
package/package.json CHANGED
@@ -1,6 +1,52 @@
1
1
  {
2
2
  "name": "@future-unknown/known",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.2.0",
4
+ "description": "Known — the command-line interface to the Known platform",
5
+ "bin": {
6
+ "known": "bin/known"
7
+ },
8
+ "files": [
9
+ "bin",
10
+ "lib"
11
+ ],
12
+ "scripts": {
13
+ "mock": "node mock/server.js",
14
+ "test": "mocha test",
15
+ "preversion": "npm test",
16
+ "version": "npm publish",
17
+ "postversion": "git push --no-verify && git push --tags --no-verify"
18
+ },
19
+ "license": "UNLICENSED",
20
+ "homepage": "https://known.info",
21
+ "repository": {
22
+ "type": "git",
23
+ "url": "git+https://github.com/future-unknown/known.git"
24
+ },
25
+ "keywords": [
26
+ "known",
27
+ "cli",
28
+ "wiki",
29
+ "agents"
30
+ ],
31
+ "engines": {
32
+ "node": ">=18"
33
+ },
34
+ "publishConfig": {
35
+ "access": "public"
36
+ },
37
+ "dependencies": {
38
+ "@colors/colors": "^1.6.0",
39
+ "@future-unknown/known-sdk": "^0.1.0",
40
+ "columnify": "^1.6.0",
41
+ "diff": "^8.0.4",
42
+ "minimist": "^1.2.8",
43
+ "open": "^8.4.2",
44
+ "time_ago_in_words": "^1.2.1"
45
+ },
46
+ "devDependencies": {
47
+ "better-sqlite3": "^13.0.3",
48
+ "code": "github:future-unknown/code#v0.1.3",
49
+ "json-rpc-2.0": "^1.7.1",
50
+ "mocha": "^10.0.0"
51
+ }
52
+ }