@unclex/ken 0.0.0-stage → 0.1.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Xiaoxing Hu
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,22 @@
1
- # Temporary Holding Version
1
+ # @unclex/ken
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ ken, the CLI of a root, a folder that is a knowledge base: what a person installs. It is
4
+ `@unclex/ken-core` plus the standard commands, bundled, each in the form of an extension
5
+ (`docs/extensions.md` at the repo root): a file this package maps a name to, run as
6
+ `ken <name>` by the runtime that runs ken. A root's `.bin/` can replace any of them.
7
+
8
+ ```sh
9
+ npm install -g @unclex/ken
10
+ npm create ken ~/ken
11
+ ```
12
+
13
+ From a clone, with no build:
14
+
15
+ ```sh
16
+ node packages/ken/src/cli.ts help
17
+ bun packages/ken/src/cli.ts version
18
+ ```
19
+
20
+ The map in `src/cli.ts` holds `status`, `log`, `digest` and `session`, a file each,
21
+ `src/ken-<name>.ts`, `dist/ken-<name>.js` in the package, and `task` (`@unclex/ken-task`) and
22
+ `lint` (`@unclex/ken-lint`), each by the `bin` of its manifest.
package/dist/cli.js ADDED
@@ -0,0 +1,26 @@
1
+ #!/usr/bin/env node
2
+ // ken: the core, with the standard commands bundled, each run as an extension
3
+ // (docs/extensions.md).
4
+ import { readFileSync } from 'node:fs';
5
+ import { dirname, extname, resolve } from 'node:path';
6
+ import { fileURLToPath } from 'node:url';
7
+ import { main } from '@unclex/ken-core';
8
+ const { name, version } = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8'));
9
+ /** The bundled commands, name to file: this package's own, ken-<name> beside this file, `.ts` in a
10
+ * clone and `.js` in a package (docs/releasing.md), and each other package's bin, never an
11
+ * import of it. */
12
+ const own = (name) => fileURLToPath(new URL(`./ken-${name}${extname(import.meta.url)}`, import.meta.url));
13
+ const entry = (pkg) => {
14
+ const manifest = fileURLToPath(import.meta.resolve(`${pkg}/package.json`));
15
+ const { bin } = JSON.parse(readFileSync(manifest, 'utf8'));
16
+ return resolve(dirname(manifest), Object.values(bin)[0] ?? '');
17
+ };
18
+ const bundled = {
19
+ status: own('status'),
20
+ log: own('log'),
21
+ digest: own('digest'),
22
+ session: own('session'),
23
+ task: entry('@unclex/ken-task'),
24
+ lint: entry('@unclex/ken-lint')
25
+ };
26
+ process.exitCode = main(process.argv.slice(2), { bundled, version: `${name} ${version}` });
@@ -0,0 +1,217 @@
1
+ // `ken digest [<transcript>]`: writes the root's record of one agent session,
2
+ // .sessions/<id>.jsonl, from the harness's transcript, KEN_SESSION_TRANSCRIPT or the argument,
3
+ // whole each time, so running it twice gives the same file. A header line, then one entry per
4
+ // line in the ghost's shape (justfiles:packages/ghost/mirror.ts#MirroredEntry): the user's
5
+ // prompts, the agent's replies with their tool calls, a name and the head of the input, and
6
+ // compactions, in transcript order; never tool results, attachments, system reminders, thinking
7
+ // or images: they are the bulk and where secrets live. `ken session` reads it. `ken log` runs
8
+ // it before each line it tags with `s=<id>`. A missing or unreadable transcript is a message
9
+ // and exit 0, so `ken log` still logs.
10
+ import { mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs';
11
+ import { join } from 'node:path';
12
+ import { cut, objects, rootOf, wantsHelp } from "./shared.js";
13
+ const args = process.argv.slice(2);
14
+ if (wantsHelp(args)) {
15
+ process.stdout.write(`Usage: ken digest [<transcript>]: writes .sessions/<id>.jsonl, the digest of one agent
16
+ session, from a Claude Code, Codex or pi transcript, KEN_SESSION_TRANSCRIPT when none is
17
+ named. \`ken log\` runs it in a session the start hook named; \`ken session <id>\` reads it.
18
+ ken digest
19
+ ken digest ~/.claude/projects/-Users-me-ken/abc-123.jsonl
20
+ `);
21
+ process.exit(0);
22
+ }
23
+ const root = rootOf('digest');
24
+ const transcript = args[0] || process.env.KEN_SESSION_TRANSCRIPT || '';
25
+ const say = (message, code) => {
26
+ process.stderr.write(`ken digest: ${message}\n`);
27
+ process.exit(code);
28
+ };
29
+ if (!transcript)
30
+ say('no transcript: KEN_SESSION_TRANSCRIPT is unset and none was given, so no digest was written. The session-start hook sets it; `ken digest <transcript>` names one.', 0);
31
+ let text = '';
32
+ try {
33
+ text = readFileSync(transcript, 'utf8');
34
+ }
35
+ catch {
36
+ say(`the transcript ${transcript} cannot be read, so no digest was written: the harness may have deleted it.`, 0);
37
+ }
38
+ const lines = objects(text);
39
+ // The format: pi's session header or Codex's session_meta is the first line; Claude Code's
40
+ // entries carry sessionId, though the first may be a file-history snapshot that has none.
41
+ const first = objects(text.slice(0, text.indexOf('\n') + 1 || undefined))[0];
42
+ const harness = first?.type === 'session' ? 'pi' : first?.type === 'session_meta' ? 'codex' : 'claude-code';
43
+ if (harness === 'claude-code' && !lines.some((e) => typeof e.sessionId === 'string'))
44
+ say(`${transcript} is no transcript ken reads (Claude Code, pi or Codex), so no digest was written.`, 0);
45
+ /** A value jq's `//` keeps: anything but null, undefined and false. */
46
+ const set = (v) => v !== null && v !== undefined && v !== false;
47
+ const or = (v, fallback) => (set(v) ? v : fallback);
48
+ const clean = (s) => s.replace(/^[ \t\n]+/, '').replace(/[ \t\n]+$/, '');
49
+ const time = (v) => (typeof v === 'string' && v !== '' ? v : null);
50
+ const blocks = (content) => Array.isArray(content) ? content.filter((b) => b && typeof b === 'object') : [];
51
+ /** Harness-made text, a background task finishing, a command output, a reminder, is not the
52
+ * user speaking. */
53
+ const spoken = (s) => !/^<(task-notification|bash-stdout|local-command-)/.test(s) &&
54
+ (harness !== 'codex' ||
55
+ !/^(<(environment_context|user_instructions|external_codex_apps_open_page)>|# AGENTS\.md instructions)/.test(s));
56
+ /** A user message: its text, a string or text blocks; a reminder the harness put in a prompt is
57
+ * cut out, wherever it sits. */
58
+ const user = (content, at) => {
59
+ const texts = (typeof content === 'string'
60
+ ? [content]
61
+ : blocks(content)
62
+ .filter((b) => b.type === 'text' || b.type === 'input_text')
63
+ .map((b) => b.text))
64
+ .filter((t) => typeof t === 'string')
65
+ .map((t) => clean(t.replace(/<system-reminder>[\s\S]*?<\/system-reminder>/g, '')))
66
+ .filter((t) => t.length > 0 && spoken(t));
67
+ return texts.length ? { kind: 'user', text: texts.join('\n\n'), at: time(at) } : undefined;
68
+ };
69
+ /** A tool call: its name and its input as JSON text, cut at 120 characters. */
70
+ const call = (id, name, input) => ({
71
+ id: or(id, ''),
72
+ name: or(name, ''),
73
+ input: cut(typeof input === 'string' ? input : JSON.stringify(input ?? null), 120)
74
+ });
75
+ const assistant = (content, at, mid) => ({
76
+ kind: 'assistant',
77
+ text: blocks(content)
78
+ .filter((b) => b.type === 'text' || b.type === 'output_text')
79
+ .map((b) => clean(String(or(b.text, ''))))
80
+ .filter((t) => t !== '')
81
+ .join('\n\n'),
82
+ toolCalls: blocks(content).flatMap((b) => b.type === 'tool_use'
83
+ ? [call(b.id, b.name, b.input)]
84
+ : b.type === 'toolCall'
85
+ ? [call(b.id, b.name, b.arguments)]
86
+ : []),
87
+ at: time(at),
88
+ mid: (mid ?? null)
89
+ });
90
+ const note = (summary, at) => ({
91
+ kind: 'compaction',
92
+ summary,
93
+ at: time(at)
94
+ });
95
+ /** Claude Code: entries in file order, one per content block, a reply its entries sharing
96
+ * message.id; isMeta text is the harness speaking, a compact summary is the model rewriting the
97
+ * past, and a rewound branch stays in the file and in the digest. */
98
+ const claude = (e) => {
99
+ if (e.type === 'system' && e.subtype === 'compact_boundary')
100
+ return note('(compacted here)', e.timestamp);
101
+ if (e.type === 'user' && e.isMeta !== true && e.isCompactSummary !== true)
102
+ return user(e.message?.content, e.timestamp);
103
+ if (e.type === 'assistant') {
104
+ const a = assistant(e.message?.content, e.timestamp, e.message?.id);
105
+ return e.isApiErrorMessage === true ? { ...a, error: or(e.error, 'error') } : a;
106
+ }
107
+ };
108
+ /** pi: a tree, id and parentId; the digest is the path from the last entry back to the root. */
109
+ const pi = (e) => {
110
+ if (e.type === 'compaction')
111
+ return note('(compacted here)', e.timestamp);
112
+ if (e.type === 'branch_summary')
113
+ return note('(branched here: the path below left another)', e.timestamp);
114
+ if (e.type !== 'message')
115
+ return;
116
+ const m = e.message ?? {};
117
+ if (m.role === 'user')
118
+ return user(m.content, e.timestamp);
119
+ if (m.role === 'assistant') {
120
+ const a = assistant(m.content, e.timestamp, null);
121
+ return m.stopReason === 'error' || m.stopReason === 'aborted'
122
+ ? { ...a, error: or(m.errorMessage, m.stopReason) }
123
+ : a;
124
+ }
125
+ };
126
+ const piPath = (all) => {
127
+ const withId = all.filter((e) => 'id' in e);
128
+ const by = new Map(withId.map((e) => [String(e.id), e]));
129
+ const path = [];
130
+ const seen = new Set();
131
+ let id = String(or(withId.at(-1)?.id, ''));
132
+ while (id !== '' && !seen.has(id)) {
133
+ seen.add(id);
134
+ const e = by.get(id);
135
+ if (e)
136
+ path.push(e);
137
+ id = String(or(e?.parentId, ''));
138
+ }
139
+ return path.reverse();
140
+ };
141
+ /** Codex: the response items in file order; a tool call is an item of its own, joined to the
142
+ * reply before it. */
143
+ const codex = (e) => {
144
+ if (e.type === 'compacted')
145
+ return note('(compacted here)', e.timestamp);
146
+ if (e.type !== 'response_item')
147
+ return;
148
+ const p = e.payload ?? {};
149
+ if (p.type === 'message' && p.role === 'user')
150
+ return user(p.content, e.timestamp);
151
+ if (p.type === 'message' && p.role === 'assistant')
152
+ return assistant(p.content, e.timestamp, null);
153
+ if (p.type === 'custom_tool_call' || p.type === 'function_call')
154
+ return {
155
+ kind: 'assistant',
156
+ text: '',
157
+ toolCalls: [call(p.call_id, p.name, or(p.input, p.arguments))],
158
+ at: time(e.timestamp),
159
+ join: true
160
+ };
161
+ };
162
+ /** The replies merged, an entry with nothing in it dropped. */
163
+ const merge = (entries) => {
164
+ const out = [];
165
+ for (const e of entries) {
166
+ const last = out.at(-1);
167
+ if (e.kind === 'assistant' &&
168
+ last?.kind === 'assistant' &&
169
+ (e.join === true || (set(e.mid) && e.mid === last.mid))) {
170
+ last.text = [last.text, e.text].filter((t) => t !== '').join('\n\n');
171
+ last.toolCalls = [...(last.toolCalls ?? []), ...(e.toolCalls ?? [])];
172
+ if (set(e.error))
173
+ last.error = e.error;
174
+ }
175
+ else
176
+ out.push({ ...e });
177
+ }
178
+ return out.filter((e) => e.kind !== 'assistant' || e.text !== '' || e.toolCalls?.length || set(e.error));
179
+ };
180
+ const emit = (session, started, cwd, entries) => {
181
+ const header = {
182
+ kind: 'session',
183
+ session: or(session, ''),
184
+ harness,
185
+ started: or(started, ''),
186
+ cwd: or(cwd, '')
187
+ };
188
+ // An entry without a time takes the one before it, the first the time the session started.
189
+ let at = time(started) ?? '';
190
+ const numbered = merge(entries.filter((e) => e !== undefined)).map(({ at: own, kind, mid: _mid, join: _join, ...rest }, i) => {
191
+ at = own ?? at;
192
+ return { id: i + 1, at, kind, ...rest };
193
+ });
194
+ return [header, ...numbered];
195
+ };
196
+ const firstString = (key) => lines.find((e) => typeof e[key] === 'string')?.[key];
197
+ const digest = harness === 'pi'
198
+ ? emit(lines[0]?.id, lines[0]?.timestamp, lines[0]?.cwd, piPath(lines).map(pi))
199
+ : harness === 'codex'
200
+ ? emit(lines[0]?.payload?.id, lines[0]?.payload?.timestamp, lines[0]?.payload?.cwd, lines.map(codex))
201
+ : emit(firstString('sessionId'), firstString('timestamp'), firstString('cwd'), lines.map(claude));
202
+ // The session ken log tags its line with; a transcript named by hand is its own session's.
203
+ const own = digest[0].session;
204
+ const id = String((args.length === 0 && process.env.KEN_SESSION) || own);
205
+ if (id === '' || id.startsWith('.') || id.includes('/') || id.includes(' '))
206
+ say(`'${id}' is no session id: it names the file .sessions/<id>.jsonl. KEN_SESSION is the harness's id, set by the session-start hook.`, 2);
207
+ const dir = join(root, '.sessions');
208
+ mkdirSync(dir, { recursive: true });
209
+ const tmp = join(dir, `.digest.${process.pid}`);
210
+ try {
211
+ writeFileSync(tmp, digest.map((e) => `${JSON.stringify(e)}\n`).join(''));
212
+ renameSync(tmp, join(dir, `${id}.jsonl`));
213
+ }
214
+ catch (e) {
215
+ rmSync(tmp, { force: true });
216
+ say(`writing ${join(dir, `${id}.jsonl`)} failed, so no digest was written: ${e.message}.`, 1);
217
+ }
@@ -0,0 +1,53 @@
1
+ // `ken log <kind> <subject> <what...>`: one line appended to the root's log.md, the timeline the
2
+ // agents write as they act, `<time> <kind> <subject>: <what>`, the time now, local, to the
3
+ // minute with its offset. One short line in one append is atomic under O_APPEND, so sessions
4
+ // logging at once never tear a line. Prints nothing on success. In a session the start hook
5
+ // named, KEN_SESSION, it first writes the session's digest with `ken digest` and ends the line
6
+ // with ` s=<id>`, the link from the line to the story behind it.
7
+ import { spawnSync } from 'node:child_process';
8
+ import { appendFileSync, readFileSync } from 'node:fs';
9
+ import { join } from 'node:path';
10
+ import { now, pointerOf, rootOf, wantsHelp } from "./shared.js";
11
+ const KINDS = ['ingest', 'query', 'page', 'task', 'promote'];
12
+ const USAGE = `Usage: ken log <kind> <subject> <what...>, e.g. \`ken log query flow/README.md answered X\`.
13
+ <kind> is one of: ${KINDS.join(' ')}. <subject> is one word grep finds the entry by: a repo key, a path
14
+ from the root, a task path, or <key>:<path>#<symbol>. <what> is one short clause. Log right
15
+ after an ingest, an answered question, a page, a task or a promote, before its commit.`;
16
+ const refuse = (message) => {
17
+ process.stderr.write(`ken log: ${message}\n${USAGE}\n`);
18
+ process.exit(2);
19
+ };
20
+ const args = process.argv.slice(2);
21
+ if (wantsHelp(args)) {
22
+ process.stdout.write(`${USAGE}\n`);
23
+ process.exit(0);
24
+ }
25
+ if (args.length < 3)
26
+ refuse('a kind, a subject and what happened are needed.');
27
+ const root = rootOf('log');
28
+ const [kind = '', subject = '', ...rest] = args;
29
+ const what = rest.join(' ');
30
+ if (!KINDS.includes(kind))
31
+ refuse(`'${kind}' is not a kind: the kinds are a closed list, so grep ' <kind> ' finds them.`);
32
+ if (subject === '' || /[ \t\n]/.test(subject))
33
+ refuse(`the subject '${subject}' is not one word: a line is split at its first spaces.`);
34
+ if (what.includes('\n'))
35
+ refuse('what happened spans lines: an entry is one line. Say it in one short clause.');
36
+ if (!/[^ \t]/.test(what))
37
+ refuse('what happened is empty.');
38
+ // A harness with no env file has its hook write the session to a pointer instead, as `ken
39
+ // status` names it.
40
+ const env = { ...process.env };
41
+ if (!env.KEN_SESSION) {
42
+ try {
43
+ const pointer = readFileSync(pointerOf(root), 'utf8');
44
+ const value = (key) => pointer.match(new RegExp(`^${key}=(.*)$`, 'm'))?.[1] ?? '';
45
+ env.KEN_SESSION = value('KEN_SESSION');
46
+ env.KEN_SESSION_TRANSCRIPT = value('KEN_SESSION_TRANSCRIPT');
47
+ }
48
+ catch { }
49
+ }
50
+ let link = '';
51
+ if (env.KEN_SESSION && spawnSync('ken', ['digest'], { stdio: 'inherit', env }).status === 0)
52
+ link = ` s=${env.KEN_SESSION}`;
53
+ appendFileSync(join(root, 'log.md'), `${now()} ${kind} ${subject}: ${what}${link}\n`);
@@ -0,0 +1,111 @@
1
+ // `ken session <id> [<range>]` prints the digest of one agent session, .sessions/<id>.jsonl, the
2
+ // story behind a log.md line that ends in s=<id>: a header line, then the last 20 entries, or
3
+ // the range, one line per entry and per tool call, as the ghost's transcript tool shows them
4
+ // (justfiles:packages/ghost/transcript-tool.ts#transcriptTool). A digest from before,
5
+ // .sessions/<id>.md, is printed whole. A search of every digest is grep's, over the files: each
6
+ // is JSON lines, one entry per line, so ken holds no search of its own. The folder is hidden, so
7
+ // a grep of the root skips it.
8
+ import { readFileSync } from 'node:fs';
9
+ import { join } from 'node:path';
10
+ import { cut, objects, rootOf, strftime, wantsHelp } from "./shared.js";
11
+ const USAGE = `Usage: \`ken session <id>\` prints the last entries of the digest a log.md line's s=<id>
12
+ names, \`ken session <id> <range>\` the entries in a range, 12, 12-30 or 1- for all. Read a
13
+ digest when its line is not enough, through ken session, never whole. To search every digest,
14
+ grep the files: .sessions/<id>.jsonl at the root, JSON lines, a header and then one entry per
15
+ line, its text JSON-escaped, a newline as \\n; a digest from before is .sessions/<id>.md.
16
+ With jq, a search prints \`<id> <n>\` per matching entry, and \`ken session <id> <n>\` reads it.
17
+ ken session 1a096823-97d3-4055-b82d-f29760687aa0 12-30
18
+ grep -il 'rayleigh' "$(ken path root)"/.sessions/*.jsonl
19
+ jq -r 'select(.id and (tostring | test("rayleigh"; "i"))) | "\\(input_filename | split("/")[-1] | rtrimstr(".jsonl")) \\(.id)"' "$(ken path root)"/.sessions/*.jsonl`;
20
+ const args = process.argv.slice(2);
21
+ if (wantsHelp(args)) {
22
+ process.stdout.write(`${USAGE}\n`);
23
+ process.exit(0);
24
+ }
25
+ const root = rootOf('session');
26
+ const dir = join(root, '.sessions');
27
+ const stop = (message, code, usage = true) => {
28
+ process.stderr.write(`${message}\n${usage ? `${USAGE}\n` : ''}`);
29
+ process.exit(code);
30
+ };
31
+ /** A line collapsed to one of 200 characters. */
32
+ const collapse = (s) => cut(s.replace(/\s+/g, ' ').replace(/^ /, '').replace(/ $/, ''), 200);
33
+ /** An ISO time as local time by `format`, `?` when it is none. */
34
+ const local = (at, format) => {
35
+ const ms = typeof at === 'string' && /^\d{4}-\d\d-\d\dT\d\d:\d\d/.test(at) ? Date.parse(at) : NaN;
36
+ return Number.isNaN(ms) ? '?' : strftime(new Date(ms), format);
37
+ };
38
+ const read = (file) => {
39
+ try {
40
+ return readFileSync(file, 'utf8');
41
+ }
42
+ catch {
43
+ return undefined;
44
+ }
45
+ };
46
+ const entries = (text) => objects(text).filter((e) => typeof e.id === 'number');
47
+ const [first = '', second = ''] = args;
48
+ if (first === '')
49
+ stop('ken session: a session id is needed.', 2);
50
+ if (first.startsWith('.') || first.includes('/'))
51
+ stop(`ken session: '${first}' is no session id: it is the word after s= in a log.md line.`, 2);
52
+ if (second.startsWith('-') || /[^0-9-]/.test(second) || /-.*-/.test(second))
53
+ stop(`ken session: '${second}' is no range: entries 12, 12-30, or 1- for all.`, 2);
54
+ if (args.length > 2)
55
+ stop('ken session: an id and at most a range are taken.', 2);
56
+ const id = first;
57
+ const range = second;
58
+ const jsonl = read(join(dir, `${id}.jsonl`));
59
+ const md = jsonl === undefined ? read(join(dir, `${id}.md`)) : undefined;
60
+ if (jsonl === undefined && md === undefined)
61
+ stop(`ken session: no digest ${id}.jsonl in ${dir}: check the id after s= in the log line, or search every digest with \`grep -l <pattern> ${dir}/*.jsonl\`.`, 1, false);
62
+ const header = objects(jsonl ?? '').find((e) => e.kind === 'session') ?? {};
63
+ const all = entries(jsonl ?? '');
64
+ const n = all.length;
65
+ const [from, to] = range === ''
66
+ ? [n - 19, n]
67
+ : range.includes('-')
68
+ ? [Number(range.split('-')[0]), range.endsWith('-') ? n : Number(range.split('-')[1])]
69
+ : [Number(range), Number(range)];
70
+ const shown = all.filter((e) => e.id >= from && e.id <= to);
71
+ /** An entry: its first line numbered and timed, a tool call a line of its own. */
72
+ const render = (e) => {
73
+ const head = `#${e.id} ${local(e.at, '%H:%M')}`;
74
+ if (e.kind === 'user')
75
+ return [`${head} user: ${e.text}`];
76
+ if (e.kind === 'assistant')
77
+ return [
78
+ ...(e.text === '' && e.toolCalls?.length ? [] : [`${head} assistant: ${e.text}`]),
79
+ ...(e.toolCalls ?? []).map((c) => collapse(`${head} → ${c.name} ${c.input}`)),
80
+ ...(e.error !== undefined && e.error !== null && e.error !== false
81
+ ? [`${head} (failed: ${e.error})`]
82
+ : [])
83
+ ];
84
+ if (e.kind === 'reset')
85
+ return [`${head} new session${e.handoff ? `: ${e.handoff}` : ''}`];
86
+ if (e.kind === 'compaction')
87
+ return [collapse(`${head} compacted: ${e.summary}`)];
88
+ return [];
89
+ };
90
+ const last = shown.at(-1);
91
+ const out = [
92
+ `Session ${header.session ?? id}, ${header.harness ?? '?'}, started ${local(header.started ?? '', '%Y-%m-%d %H:%M')}, ${n} entries${!last
93
+ ? `, none in ${range}: \`ken session ${id} 1-\` prints them all.`
94
+ : shown.length === n
95
+ ? ', all shown.'
96
+ : range === ''
97
+ ? `, the last ${shown.length} shown: \`ken session ${id} <range>\` prints others, 12, 12-30, or 1- for all.`
98
+ : `, ${shown[0]?.id}-${last.id} shown: \`ken session ${id} 1-\` prints all.`}`
99
+ ];
100
+ // A day line before the first entry and where the day changes.
101
+ let day;
102
+ for (const e of shown) {
103
+ const d = local(e.at, '%Y-%m-%d');
104
+ if (d !== day)
105
+ out.push(d);
106
+ day = d;
107
+ out.push(...render(e));
108
+ }
109
+ // No process.exit after it: a large digest into a pipe takes more than one write, and an exit
110
+ // drops what is not written yet.
111
+ process.stdout.write(md ?? `${out.join('\n')}\n`);
@@ -0,0 +1,97 @@
1
+ // `ken status`, the session-start hook: one screen of what this root holds, so the agent never
2
+ // lists folders, and the root's .bin/ on the PATH of the agent's shell where the harness has a
3
+ // way. Exit 0 always: the output is the agent's context, the errors included.
4
+ import { spawnSync } from 'node:child_process';
5
+ import { appendFileSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
6
+ import { dirname, join } from 'node:path';
7
+ import { now, pointerOf, wantsHelp } from "./shared.js";
8
+ if (wantsHelp(process.argv.slice(2))) {
9
+ process.stdout.write(`Usage: ken status: the session-start hook's screen, the repos, the settings, the ready
10
+ tasks and the last lines of log.md. Run by the hook with its JSON on stdin, it also gives
11
+ the session's shell the root's .bin/ on PATH and the session for \`ken log\`, through
12
+ CLAUDE_ENV_FILE where the harness sets it, else a pointer under ~/.local/state/ken.
13
+ ken status
14
+ `);
15
+ process.exit(0);
16
+ }
17
+ const out = [];
18
+ const say = (s = '') => out.push(`${s}\n`);
19
+ /** `ken <args>` with its stderr in its stdout, as `2>&1` gives them. */
20
+ const ken = (...args) => spawnSync('sh', ['-c', 'ken "$@" 2>&1', 'ken', ...args], {
21
+ encoding: 'utf8',
22
+ stdio: ['ignore', 'pipe', 'inherit']
23
+ }).stdout ?? '';
24
+ const root = process.env.KEN_ROOT;
25
+ if (!root) {
26
+ process.stdout.write(`This is no ken root: ken found no .ken at or above ${process.cwd()}, so there is nothing to show. Its CLI is \`ken\`; \`ken help\` lists the commands, and \`ken init\` makes a root.\n`);
27
+ process.exit(0);
28
+ }
29
+ /** Text a shell reads back as one word, inside single quotes. */
30
+ const q = (s) => `'${s.replaceAll("'", "'\\''")}'`;
31
+ // The hook's stdin JSON names the session and its transcript, which `ken log` needs for the
32
+ // digest; a person running it at a terminal sends none.
33
+ let input = {};
34
+ if (!process.stdin.isTTY) {
35
+ try {
36
+ const v = JSON.parse(readFileSync(0, 'utf8'));
37
+ if (v && typeof v === 'object')
38
+ input = v;
39
+ }
40
+ catch { }
41
+ }
42
+ const session = typeof input.session_id === 'string' ? input.session_id : '';
43
+ const transcript = typeof input.transcript_path === 'string' ? input.transcript_path : '';
44
+ // Claude Code sources CLAUDE_ENV_FILE before each shell command: the root's .bin/ goes on its
45
+ // PATH, for the root's own tools; `ken` finds the root from any folder under it. A harness with
46
+ // no such file gets the session in a pointer `ken log` reads when the environment has none.
47
+ const pointer = pointerOf(root);
48
+ try {
49
+ const envFile = process.env.CLAUDE_ENV_FILE;
50
+ if (envFile) {
51
+ appendFileSync(envFile, `export PATH=${q(join(root, '.bin'))}:"$PATH"\n`);
52
+ if (session)
53
+ appendFileSync(envFile, `export KEN_SESSION=${q(session)} KEN_SESSION_TRANSCRIPT=${q(transcript)}\n`);
54
+ }
55
+ else if (session) {
56
+ mkdirSync(dirname(pointer), { recursive: true });
57
+ writeFileSync(pointer, `KEN_SESSION=${session}\nKEN_SESSION_TRANSCRIPT=${transcript}\n`);
58
+ }
59
+ else if ('hook_event_name' in input) {
60
+ // a hook that names no session, pi's shim, starts one all the same: the file is stale
61
+ rmSync(pointer, { force: true });
62
+ }
63
+ }
64
+ catch (e) {
65
+ say(`ken status: the session was not passed on: ${e.message}.`);
66
+ }
67
+ say(`This is a ken root: ${root}. Its CLI is \`ken\`; \`ken help\` lists the commands.`);
68
+ say();
69
+ out.push(ken('repos'));
70
+ say();
71
+ say('Settings, .ken:');
72
+ try {
73
+ for (const line of readFileSync(join(root, '.ken'), 'utf8').replace(/\n$/, '').split('\n'))
74
+ say(` ${line}`);
75
+ }
76
+ catch (e) {
77
+ say(` ${e.message}`);
78
+ }
79
+ // The ready tasks: `ken task` is bundled, or the root's .bin/ replaces it.
80
+ say();
81
+ out.push(ken('task', 'ready'));
82
+ // The last entries of the timeline the agents write with `ken log`, never the whole file. A
83
+ // union merge can leave lines out of order; sorting puts back those that share an offset.
84
+ let log = '';
85
+ try {
86
+ log = readFileSync(join(root, 'log.md'), 'utf8');
87
+ }
88
+ catch { }
89
+ if (log) {
90
+ say();
91
+ say(`Recent, log.md (now ${now()}); grep it for older entries, never read it whole:`);
92
+ const lines = log.replace(/\n$/, '').split('\n');
93
+ lines.sort((a, b) => Buffer.compare(Buffer.from(a), Buffer.from(b)));
94
+ for (const line of lines.slice(-10))
95
+ say(line);
96
+ }
97
+ process.stdout.write(out.join(''));
package/dist/shared.js ADDED
@@ -0,0 +1,51 @@
1
+ // What the standard commands share. Each is an extension (docs/extensions.md): the root from
2
+ // KEN_ROOT, the core only through `ken`, so nothing here imports @unclex/ken-core.
3
+ import { join } from 'node:path';
4
+ /** The root ken found, or a message on stderr and exit 2 when `ken` ran outside any root. */
5
+ export const rootOf = (name) => {
6
+ const root = process.env.KEN_ROOT;
7
+ if (root)
8
+ return root;
9
+ process.stderr.write(`ken ${name}: there is no root here: KEN_ROOT is unset, as \`ken\` found no .ken at or above ${process.cwd()}. cd into a root and run \`ken ${name}\` again, or \`ken init\` to make one.\n`);
10
+ process.exit(2);
11
+ };
12
+ /** Where a harness with no environment file keeps the session for `ken log`: machine-local
13
+ * state, out of the root, one per root named by its path with / as -. */
14
+ export const pointerOf = (root) => join(process.env.HOME ?? '', '.local/state/ken', root.replaceAll('/', '-'));
15
+ const pad = (n) => String(n).padStart(2, '0');
16
+ /** `d` in local time by a strftime format of %Y %m %d %H %M %z only. */
17
+ export const strftime = (d, format) => {
18
+ const offset = -d.getTimezoneOffset();
19
+ const z = `${offset < 0 ? '-' : '+'}${pad(Math.trunc(Math.abs(offset) / 60))}${pad(Math.abs(offset) % 60)}`;
20
+ const parts = {
21
+ Y: String(d.getFullYear()),
22
+ m: pad(d.getMonth() + 1),
23
+ d: pad(d.getDate()),
24
+ H: pad(d.getHours()),
25
+ M: pad(d.getMinutes()),
26
+ z
27
+ };
28
+ return format.replace(/%([YmdHMz])/g, (_, c) => parts[c] ?? '');
29
+ };
30
+ /** Now, as log.md stamps it: local, to the minute, with the offset. */
31
+ export const now = () => strftime(new Date(), '%Y-%m-%dT%H:%M%z');
32
+ /** A string, cut to `max` characters, counted as code points, with … when cut. */
33
+ export const cut = (s, max) => {
34
+ const chars = Array.from(s);
35
+ return chars.length > max ? `${chars.slice(0, max).join('')}…` : s;
36
+ };
37
+ /** The objects of a JSON-lines text; a line that is not one, as one still being written, is
38
+ * skipped. */
39
+ export const objects = (text) => text.split('\n').flatMap((line) => {
40
+ if (!line)
41
+ return [];
42
+ try {
43
+ const v = JSON.parse(line);
44
+ return v && typeof v === 'object' && !Array.isArray(v) ? [v] : [];
45
+ }
46
+ catch {
47
+ return [];
48
+ }
49
+ });
50
+ /** Whether `args` asks for the usage: the one argument --help or -h. */
51
+ export const wantsHelp = (args) => args.length === 1 && (args[0] === '--help' || args[0] === '-h');
package/package.json CHANGED
@@ -1,6 +1,31 @@
1
1
  {
2
2
  "name": "@unclex/ken",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.1.1",
4
+ "description": "ken, the CLI of a root, a folder that is a knowledge base: the core and the standard commands.",
5
+ "type": "module",
6
+ "license": "MIT",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "git+https://github.com/xiaoxinghu/ken.git",
10
+ "directory": "packages/ken"
11
+ },
12
+ "homepage": "https://unclex.net",
13
+ "bin": {
14
+ "ken": "./dist/cli.js"
15
+ },
16
+ "files": [
17
+ "dist"
18
+ ],
19
+ "engines": {
20
+ "node": ">=24"
21
+ },
22
+ "publishConfig": {
23
+ "access": "public"
24
+ },
25
+ "dependencies": {
26
+ "@unclex/ken-core": "0.1.1",
27
+ "@unclex/ken-lint": "0.1.1",
28
+ "@unclex/ken-task": "0.1.1"
29
+ },
30
+ "scripts": {}
6
31
  }