djournal 0.11.0 → 0.12.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/README.md CHANGED
@@ -163,9 +163,18 @@ Requires Node.js 18 or newer. Run this from the project you want to equip:
163
163
 
164
164
  ```bash
165
165
  npm install -g djournal
166
- djournal install
166
+ djournal
167
167
  ```
168
168
 
169
+ Run `djournal` or `journal` without arguments to open the interactive journal.
170
+ Browse work, search with Recall, open entries in your editor, manage sharing,
171
+ and inspect project status. Installation, configuration, upgrades, diagnostics,
172
+ and uninstall are available from the same menu. `djournal setup` remains an
173
+ explicit way to open it, including `--target /path/to/project`.
174
+
175
+ Existing commands remain available for direct use and automation. The wizard
176
+ requires an interactive terminal; use `djournal --help` to see the commands.
177
+
169
178
  The global install gives you the `djournal` and `journal` commands. The
170
179
  installer targets the current directory and detects Codex, Claude Code, Pi, or
171
180
  a `.grokbot/` marker. Select explicitly when needed:
package/bin/journal.js CHANGED
@@ -25,6 +25,9 @@ const sourceRoot = path.resolve(__dirname, "..");
25
25
 
26
26
  function usage() {
27
27
  return `Usage:
28
+ djournal Open the interactive journal
29
+ journal Alias for djournal
30
+ journal setup [--target DIR]
28
31
  journal install [--target DIR] [--harness LIST | --all | --instructions-only]
29
32
  journal upgrade [--target DIR]
30
33
  journal uninstall [--target DIR] [--harness LIST | --all]
@@ -64,8 +67,9 @@ Options:
64
67
 
65
68
  function parseArgs(argv) {
66
69
  const args = [...argv];
67
- const command = args.shift();
68
- if (!command || !["install", "upgrade", "uninstall", "status", "doctor", "config", "share", "pull", "sync", "update", "work", "recall"].includes(command)) {
70
+ const command = args.length ? args.shift() : "setup";
71
+ if (["--help", "-h"].includes(command)) throw new InstallerError(usage(), "HELP");
72
+ if (!["setup", "install", "upgrade", "uninstall", "status", "doctor", "config", "share", "pull", "sync", "update", "work", "recall"].includes(command)) {
69
73
  throw new InstallerError(usage(), "USAGE");
70
74
  }
71
75
  const options = { command, harnesses: [] };
@@ -89,6 +93,9 @@ function parseArgs(argv) {
89
93
  }
90
94
  while (args.length) {
91
95
  const arg = args.shift();
96
+ if (command === "setup" && !["--target", "--help", "-h"].includes(arg) && !arg.startsWith("--target=")) {
97
+ throw new InstallerError("setup supports only --target and --help; use direct commands for automation", "USAGE");
98
+ }
92
99
  if (command === "recall" && options.subcommand === "files" && arg === "--") {
93
100
  (options.paths ||= []).push(...args.splice(0));
94
101
  } else if (arg === "--repository") {
@@ -182,95 +189,103 @@ function parseArgs(argv) {
182
189
  return options;
183
190
  }
184
191
 
185
- function print(value, json) {
192
+ function print(value, json, output = process.stdout) {
186
193
  if (json) {
187
- process.stdout.write(`${JSON.stringify(value, null, 2)}\n`);
194
+ output.write(`${JSON.stringify(value, null, 2)}\n`);
188
195
  return;
189
196
  }
190
197
  if (value.action === "update-check") {
191
- process.stdout.write(`cli version: ${value.cliVersion || "unknown"}\n`);
192
- if (value.projectVersion) process.stdout.write(`project assets: ${value.projectVersion}\n`);
193
- process.stdout.write(`latest version: ${value.latestVersion || "unknown"}\n`);
194
- if (value.updateAvailable) process.stdout.write(`update available: ${value.cliVersion} -> ${value.latestVersion}\n`);
195
- else if (value.latestVersion) process.stdout.write("djournal CLI is up to date\n");
196
- if (value.projectUpdateAvailable) process.stdout.write(`project upgrade available: ${value.projectVersion} -> ${value.cliVersion}\n`);
197
- if (value.checkedAt) process.stdout.write(`checked: ${value.checkedAt}\n`);
198
+ output.write(`cli version: ${value.cliVersion || "unknown"}\n`);
199
+ if (value.projectVersion) output.write(`project assets: ${value.projectVersion}\n`);
200
+ output.write(`latest version: ${value.latestVersion || "unknown"}\n`);
201
+ if (value.updateAvailable) output.write(`update available: ${value.cliVersion} -> ${value.latestVersion}\n`);
202
+ else if (value.latestVersion) output.write("djournal CLI is up to date\n");
203
+ if (value.projectUpdateAvailable) output.write(`project upgrade available: ${value.projectVersion} -> ${value.cliVersion}\n`);
204
+ if (value.checkedAt) output.write(`checked: ${value.checkedAt}\n`);
198
205
  return;
199
206
  }
200
207
  if (value.action === "work-list") {
201
- if (value.selected) process.stdout.write(`selected: ${value.selected}\n`);
208
+ if (value.selected) output.write(`selected: ${value.selected}\n`);
202
209
  for (const item of value.workItems || []) {
203
210
  const marker = item.selected ? "*" : " ";
204
- process.stdout.write(`${marker} ${item.slug} [${item.status}] ${item.title}\n`);
211
+ output.write(`${marker} ${item.slug} [${item.status}] ${item.title}\n`);
205
212
  }
206
213
  return;
207
214
  }
208
215
  if (value.action === "work-bind") {
209
- process.stdout.write(`bound ${value.work} to session ${value.sessionHash}\n`);
216
+ output.write(`bound ${value.work} to session ${value.sessionHash}\n`);
210
217
  return;
211
218
  }
212
219
  if (value.action === "recall-files") {
213
- process.stdout.write(`recall files: ${value.cache.status} (${value.cache.mode}), ${value.entries.length}/${value.totalEntries} entries\n`);
220
+ output.write(`recall files: ${value.cache.status} (${value.cache.mode}), ${value.entries.length}/${value.totalEntries} entries\n`);
214
221
  for (const entry of value.entries) {
215
- process.stdout.write(`${entry.path} ${entry.title}\n`);
222
+ output.write(`${entry.path} ${entry.title}\n`);
216
223
  for (const match of entry.matches) {
217
224
  const detail = match.kind === "linked_context" ? `via ${match.viaPath}` : `${match.recordedPath} (${match.scope}, ${match.evidence.provenance})`;
218
- process.stdout.write(` ${match.inputPath}: ${match.kind} — ${detail}\n`);
225
+ output.write(` ${match.inputPath}: ${match.kind} — ${detail}\n`);
219
226
  }
220
- for (const replacement of entry.supersededBy) process.stdout.write(` superseded by: ${replacement.path}\n`);
221
- if (entry.matchesTruncated || entry.codeReferencesTruncated || entry.supersededByTruncated) process.stdout.write(" additional entry evidence truncated\n");
227
+ for (const replacement of entry.supersededBy) output.write(` superseded by: ${replacement.path}\n`);
228
+ if (entry.matchesTruncated || entry.codeReferencesTruncated || entry.supersededByTruncated) output.write(" additional entry evidence truncated\n");
222
229
  }
223
- if (value.unmatchedPaths.length) process.stdout.write(`no indexed evidence: ${value.unmatchedPaths.join(", ")}\n`);
224
- if (value.truncated || value.relatedTruncated) process.stdout.write("results or linked context truncated; narrow paths or raise --limit\n");
225
- for (const item of value.warnings) process.stdout.write(`warning: ${item.code}\n`);
226
- process.stdout.write("Evidence candidates only; read canonical entries before assessing the change.\n");
230
+ if (value.unmatchedPaths.length) output.write(`no indexed evidence: ${value.unmatchedPaths.join(", ")}\n`);
231
+ if (value.truncated || value.relatedTruncated) output.write("results or linked context truncated; narrow paths or raise --limit\n");
232
+ for (const item of value.warnings) output.write(`warning: ${item.code}\n`);
233
+ output.write("Evidence candidates only; read canonical entries before assessing the change.\n");
227
234
  return;
228
235
  }
229
236
  if (value.action === "recall-index") {
230
- process.stdout.write(`recall index: ${value.cache.status} (${value.cache.mode})\n`);
231
- process.stdout.write(`documents: ${value.cache.documentCount}\n`);
232
- process.stdout.write(`elapsed: ${value.cache.totalMs.toFixed(1)} ms\n`);
233
- for (const item of value.warnings || []) process.stdout.write(`warning: ${item.code}${item.path ? ` ${item.path}` : ""}${item.detail ? ` - ${item.detail}` : ""}\n`);
237
+ output.write(`recall index: ${value.cache.status} (${value.cache.mode})\n`);
238
+ output.write(`documents: ${value.cache.documentCount}\n`);
239
+ output.write(`elapsed: ${value.cache.totalMs.toFixed(1)} ms\n`);
240
+ for (const item of value.warnings || []) output.write(`warning: ${item.code}${item.path ? ` ${item.path}` : ""}${item.detail ? ` - ${item.detail}` : ""}\n`);
234
241
  return;
235
242
  }
236
243
  if (value.action === "recall-search") {
237
- process.stdout.write(`recall search: ${value.cache.status} (${value.cache.mode}), ${value.cache.totalMs.toFixed(1)} ms\n`);
244
+ output.write(`recall search: ${value.cache.status} (${value.cache.mode}), ${value.cache.totalMs.toFixed(1)} ms\n`);
238
245
  for (const item of [...(value.workItems || []), ...(value.entries || [])]) {
239
- process.stdout.write(`${item.score.toFixed(2).padStart(8)} ${item.path} ${item.title}\n`);
246
+ output.write(`${item.score.toFixed(2).padStart(8)} ${item.path} ${item.title}\n`);
240
247
  }
241
- for (const item of value.warnings || []) process.stdout.write(`warning: ${item.code}${item.path ? ` ${item.path}` : ""}${item.detail ? ` - ${item.detail}` : ""}\n`);
248
+ for (const item of value.warnings || []) output.write(`warning: ${item.code}${item.path ? ` ${item.path}` : ""}${item.detail ? ` - ${item.detail}` : ""}\n`);
242
249
  return;
243
250
  }
244
- if (value.action) process.stdout.write(`${value.action}: ${value.target}\n`);
245
- else if (typeof value.installed === "boolean") process.stdout.write(value.installed ? `installed: ${value.target}\n` : `not installed: ${value.target}\n`);
246
- else process.stdout.write(`${value.ok ? "ok" : "failed"}: ${value.target}\n`);
247
- if (value.harnesses) process.stdout.write(`harnesses: ${value.harnesses.join(", ") || "instructions-only"}\n`);
248
- if (value.key) process.stdout.write(`${value.key}: ${JSON.stringify(value.value)}\n`);
249
- else if (value.config) process.stdout.write(`${JSON.stringify(value.config, null, 2)}\n`);
250
- if (value.cliVersion) process.stdout.write(`cli version: ${value.cliVersion}\n`);
251
- if (value.projectVersion) process.stdout.write(`project assets: ${value.projectVersion}\n`);
252
- if (value.latestVersion) process.stdout.write(`latest version: ${value.latestVersion}\n`);
253
- if (value.updateAvailable) process.stdout.write("update available: yes\n");
254
- if (value.projectUpdateAvailable) process.stdout.write("project upgrade available: yes\n");
251
+ if (value.action) output.write(`${value.action}: ${value.target}\n`);
252
+ else if (typeof value.installed === "boolean") output.write(value.installed ? `installed: ${value.target}\n` : `not installed: ${value.target}\n`);
253
+ else output.write(`${value.ok ? "ok" : "failed"}: ${value.target}\n`);
254
+ if (value.harnesses) output.write(`harnesses: ${value.harnesses.join(", ") || "instructions-only"}\n`);
255
+ if (value.key) output.write(`${value.key}: ${JSON.stringify(value.value)}\n`);
256
+ else if (value.config) output.write(`${JSON.stringify(value.config, null, 2)}\n`);
257
+ if (value.cliVersion) output.write(`cli version: ${value.cliVersion}\n`);
258
+ if (value.projectVersion) output.write(`project assets: ${value.projectVersion}\n`);
259
+ if (value.latestVersion) output.write(`latest version: ${value.latestVersion}\n`);
260
+ if (value.updateAvailable) output.write("update available: yes\n");
261
+ if (value.projectUpdateAvailable) output.write("project upgrade available: yes\n");
255
262
  if (value.recallCache) {
256
263
  const cache = value.recallCache;
257
- process.stdout.write(`recall cache: ${cache.valid ? `${cache.documentCount} documents, ${cache.indexVersion}` : (cache.exists ? "invalid; rebuilds on next recall" : "not built")}\n`);
264
+ output.write(`recall cache: ${cache.valid ? `${cache.documentCount} documents, ${cache.indexVersion}` : (cache.exists ? "invalid; rebuilds on next recall" : "not built")}\n`);
258
265
  }
259
266
  if (value.workItems) {
260
267
  for (const item of value.workItems) {
261
- process.stdout.write(`${item.changed ? "shared" : "unchanged"} ${item.work}\n`);
262
- if (item.warning) process.stdout.write(`warning: ${item.warning}\n`);
268
+ if (typeof item === "string") {
269
+ output.write(`${item}\n`);
270
+ continue;
271
+ }
272
+ output.write(`${item.changed ? "shared" : "unchanged"} ${item.work}\n`);
273
+ if (item.warning) output.write(`warning: ${item.warning}\n`);
263
274
  }
264
275
  }
265
- if (value.conflicts?.length) process.stdout.write(`conflicts: ${value.conflicts.join(", ")}\n`);
276
+ if (value.work) output.write(`work: ${value.work}\n`);
277
+ if (value.shared) output.write("marked for sharing\n");
278
+ if (value.skipped) output.write(`skipped: ${value.reason || "no changes required"}\n`);
279
+ if (value.warning) output.write(`warning: ${value.warning}\n`);
280
+ if (value.conflicts?.length) output.write(`conflicts: ${value.conflicts.join(", ")}\n`);
266
281
  if (value.files) {
267
282
  for (const file of value.files) {
268
- if (typeof file === "string") process.stdout.write(`${file}\n`);
269
- else process.stdout.write(`${file.status.padEnd(8)} ${file.path}\n`);
283
+ if (typeof file === "string") output.write(`${file}\n`);
284
+ else output.write(`${file.status.padEnd(8)} ${file.path}\n`);
270
285
  }
271
286
  }
272
287
  if (value.checks) {
273
- for (const check of value.checks) process.stdout.write(`${check.ok ? "ok" : "fail"} ${check.name}: ${check.detail}\n`);
288
+ for (const check of value.checks) output.write(`${check.ok ? "ok" : "fail"} ${check.name}: ${check.detail}\n`);
274
289
  }
275
290
  }
276
291
 
@@ -307,6 +322,13 @@ function launchUpdateRefresh(options, runner = spawn) {
307
322
  async function main() {
308
323
  try {
309
324
  const options = parseArgs(process.argv.slice(2));
325
+ if (options.command === "setup") {
326
+ const { setup } = require("../lib/setup.js");
327
+ const result = await setup(options, { print });
328
+ if (result.cancelled) process.exitCode = 130;
329
+ else if (result.failed) process.exitCode = 2;
330
+ return;
331
+ }
310
332
  let result;
311
333
  if (options.command === "install") result = await install(options);
312
334
  else if (options.command === "upgrade") result = await upgrade(options);
@@ -11,16 +11,125 @@ carry journal memory. The installed project gets harness integration plus a
11
11
  npm install -g djournal
12
12
  ```
13
13
 
14
- Then run the installer from the repository or journal workspace you want to
15
- equip:
14
+ Then open the interactive journal from your repository or journal workspace:
16
15
 
17
16
  ```bash
18
- djournal install
17
+ djournal
19
18
  ```
20
19
 
21
20
  The package exposes both `djournal` and `journal` commands. They point to the
22
21
  same CLI.
23
22
 
23
+ ## Interactive journal
24
+
25
+ Run `djournal` or `journal` without arguments in an interactive terminal.
26
+ `djournal setup` remains supported; use `djournal setup --target /path/to/project`
27
+ to open another project. Use the arrow keys and Enter to choose an option.
28
+
29
+ Each new question or menu replaces the previous screen. The project header stays
30
+ visible, and new results, errors, and confirmation details appear above the next
31
+ prompt until you continue. Returning from an editor redraws the entry picker.
32
+ A mark of two offset journal pages and a bookmark heads the wizard, beside the
33
+ djournal wordmark. Search, filters, and smaller terminals use a small document
34
+ symbol and the wordmark.
35
+ `TERM=dumb` uses an ASCII version of the mark.
36
+ Menus show short labels and details for the highlighted item; long paths wrap
37
+ instead of widening the menu. The list height adapts to the terminal size.
38
+ Color is optional: `NO_COLOR=1 djournal` uses plain text, and selection and
39
+ checkbox markers remain visible without color.
40
+
41
+ - **List:** choose a work item, then open an entry in your editor, share, pull, sync, or bind an active item to
42
+ an agent session. Sharing marks the item; Sync copies it to the Git projection.
43
+ If synchronization is disabled, the wizard offers configuration first.
44
+ - **Recall:** search journal knowledge across work items and open matching
45
+ entries or work descriptions in your editor. Press Tab to adjust filters, or refresh/rebuild the search index from the Recall menu.
46
+ - **Status:** inspect the project's installation, integrations, and versions.
47
+ - **Install:** select Codex, Claude Code, Pi, Grok Bot, a custom combination, all
48
+ supported integrations, or instructions only. After installation, configure the project.
49
+ Existing integrations are retained on an already installed project.
50
+ - **Configure:** keep work local, share through the project repository, or use
51
+ a separate existing journal Git repository. Set automatic sync for standalone
52
+ mode and choose update notifications and their frequency. Current values are
53
+ defaults; review the proposed changes before saving.
54
+ - **Upgrade:** refresh installed project assets with the installed CLI version.
55
+ - **Update:** run the existing `update check` operation. If a newer CLI is
56
+ available, show the npm update command; the wizard does not install packages.
57
+ - **Doctor:** run the existing project health checks.
58
+ - **Uninstall:** remove one integration or all installed assets after confirmation.
59
+ Journal history is kept; modified installed files are preserved and reported.
60
+
61
+ Press **Escape** to go back to the parent menu from any prompt. From a work's
62
+ actions it returns to the work picker; from the entry picker it returns to that
63
+ work's actions. In an unfinished install, configuration, or work action, Escape
64
+ discards the pending answers and returns to the menu that launched it. At the
65
+ main menu, Escape stays there. Completed operations remain applied.
66
+
67
+ Menus also have Back and Exit choices. Use Space to toggle integrations in the
68
+ checkbox list; detected integrations start selected. Enter accepts the current
69
+ selection or displayed default. Ctrl-C, Ctrl-D, or end-of-input cancels. Completed operations remain applied, while
70
+ configuration answers are saved only after confirmation. A failed operation
71
+ returns to the main menu with an error; the process exits with code 2 if an
72
+ operation failed, or 130 on cancellation.
73
+
74
+ The wizard requires terminal input and output. An argument-free invocation in a
75
+ pipe or script returns an interactive-terminal error instead of waiting for input.
76
+ The explicit `setup` command accepts only `--target` and `--help`.
77
+ All existing commands continue to work directly, including JSON and dry runs.
78
+ Use `djournal --help` for the command list.
79
+ For example, `djournal install --all` installs directly without the wizard.
80
+
81
+ ### Recall from the wizard
82
+
83
+ Choose **Recall → Search journal** and start typing. Results update in place
84
+ after a 250 ms pause; you do not need to submit the query. Use Up/Down to select
85
+ a result and Enter to open its canonical Markdown file in your editor. Close
86
+ the editor to return to the same query and refreshed results. Both entries and
87
+ work descriptions are searched, including completed work; the current session binding does not silently restrict the search.
88
+
89
+ Keep typing to change the query. Press **Tab** at any time to open the filter
90
+ panel, including while results load. All filters appear together: work item,
91
+ result kind, entry type, work status, visibility, and maximum results per kind.
92
+ Use **Up/Down** to choose a field and **Left/Right** to adjust it. On the result
93
+ limit row, you can also type a number from 1 to 100. **Enter** applies the draft
94
+ and returns to the same query; **Escape** discards it. **Ctrl-R** resets the draft
95
+ to defaults, which you can apply or discard.
96
+
97
+ The search screen shows the current scope and a compact, paged list of matches.
98
+ Filter controls are separate from matches. Previous matches remain dimmed while
99
+ updating and cannot be opened until the new search finishes. Blank queries skip
100
+ searching; Tab still opens filters and Escape returns to Recall.
101
+
102
+ **Refresh index** updates the cache from the journal. **Rebuild index** recreates
103
+ it after confirmation. These use the same services as `djournal recall index`
104
+ and `djournal recall index --rebuild`; they do not rewrite journal entries.
105
+
106
+ ### Open journal entries in your editor
107
+
108
+ Choose **List → a work item → Open entry in editor**. The picker lists journal,
109
+ research, documentation, and decision entries, newest first, with their dates,
110
+ types, titles, and filenames. It reads the canonical journal store configured by
111
+ `.djournal.json`, with support for legacy local journals. Sharing does not need
112
+ to be enabled.
113
+
114
+ The editor is selected from `$VISUAL`, then `$EDITOR`, falling back to `vi`
115
+ (`notepad` on Windows). For example:
116
+
117
+ ```bash
118
+ export EDITOR='nano'
119
+ export VISUAL='vim -R'
120
+ djournal
121
+ ```
122
+
123
+ Quoted executable paths and arguments are supported, such as
124
+ `VISUAL='"/path with spaces/editor" --wait'`. Commands run directly; shell aliases,
125
+ pipes, variable expansion, and other shell expressions are not evaluated. Use a
126
+ waiting mode such as `code --wait` for an editor that otherwise returns immediately.
127
+
128
+ Close the editor to return to the entry picker. The canonical Markdown file is
129
+ opened directly, so saving edits changes the journal; use your editor's read-only
130
+ flag if desired. The wizard does not rewrite entry metadata. If an editor cannot
131
+ start or exits unsuccessfully, the picker remains available for retry or Escape.
132
+
24
133
  ## No global install
25
134
 
26
135
  Use `npx` when you want a one-off install without adding a global command:
@@ -0,0 +1,108 @@
1
+ "use strict";
2
+
3
+ const fs = require("node:fs");
4
+ const path = require("node:path");
5
+ const { spawnSync } = require("node:child_process");
6
+ const { InstallerError, projectContext } = require("./installer/index.js");
7
+ const { ENTRY_DIRECTORIES, documentFromDescriptor } = require("./recall/corpus.js");
8
+
9
+ // Reject symlinked components both while listing and immediately before opening.
10
+ function entryPath(root, relative) {
11
+ const parts = relative.split("/");
12
+ if (path.isAbsolute(relative) || parts.some((part) => !part || part === "." || part === ".." || part.includes("\\"))) {
13
+ throw new InstallerError("Entry path must stay inside its work item", "UNSAFE_PATH");
14
+ }
15
+ let file = root;
16
+ for (const part of parts) {
17
+ file = path.join(file, part);
18
+ if (fs.lstatSync(file).isSymbolicLink()) throw new InstallerError("Symbolic links cannot be opened as journal entries", "UNSAFE_PATH");
19
+ }
20
+ return file;
21
+ }
22
+
23
+ function listEntries(options) {
24
+ const context = projectContext(path.resolve(options.target), options);
25
+ if (!options.work || /[/\\]/.test(options.work) || [".", ".."].includes(options.work)) {
26
+ throw new InstallerError("Invalid work item", "INVALID_WORK");
27
+ }
28
+ const root = path.resolve(context.journalRoot);
29
+ const workRelative = `work/${options.work}`;
30
+ entryPath(root, workRelative);
31
+ const records = [];
32
+ function walk(relative, area) {
33
+ const directory = entryPath(root, relative);
34
+ for (const item of fs.readdirSync(directory, { withFileTypes: true })) {
35
+ if (item.isSymbolicLink()) continue;
36
+ const child = `${relative}/${item.name}`;
37
+ if (item.isDirectory()) walk(child, area);
38
+ else if (item.isFile() && path.extname(item.name).toLowerCase() === ".md") {
39
+ const absolute = entryPath(root, child);
40
+ const { document } = documentFromDescriptor({ absolute, relative: child, area, kind: "entry", workSlug: options.work }, new Map(), []);
41
+ const fallback = item.name.match(/^\d{4}-\d{2}-\d{2}/)?.[0] || "";
42
+ const date = Number.isFinite(Date.parse(document.createdAt)) ? document.createdAt : fallback;
43
+ records.push({ root, relative: child, title: document.title, entryType: document.entryType, date });
44
+ }
45
+ }
46
+ }
47
+ for (const area of ENTRY_DIRECTORIES) {
48
+ const relative = `${workRelative}/${area}`;
49
+ try {
50
+ const stat = fs.lstatSync(path.join(root, relative));
51
+ if (stat.isDirectory() && !stat.isSymbolicLink()) walk(relative, area);
52
+ } catch (error) { if (error.code !== "ENOENT") throw error; }
53
+ }
54
+ return records.sort((a, b) => b.date.localeCompare(a.date) || b.relative.localeCompare(a.relative));
55
+ }
56
+
57
+ // Parse an executable and arguments, not a shell program. Keep filename data
58
+ // out of shell evaluation, including spaces, quotes, and command substitutions.
59
+ function editorArgs(command) {
60
+ const args = [];
61
+ let word = "", quote = "", started = false;
62
+ for (let i = 0; i < command.length; i += 1) {
63
+ const char = command[i];
64
+ if (char === "\\" && quote !== "'" && i + 1 < command.length &&
65
+ (/[\s\\'"]/.test(command[i + 1]))) {
66
+ word += command[++i]; started = true;
67
+ } else if (quote) {
68
+ if (char === quote) quote = "";
69
+ else word += char;
70
+ } else if (char === "'" || char === '"') {
71
+ quote = char; started = true;
72
+ } else if (/\s/.test(char)) {
73
+ if (started) { args.push(word); word = ""; started = false; }
74
+ } else { word += char; started = true; }
75
+ }
76
+ if (quote) throw new InstallerError("Unclosed quote in VISUAL or EDITOR", "EDITOR_CONFIG");
77
+ if (started) args.push(word);
78
+ if (!args[0]) throw new InstallerError("Set VISUAL or EDITOR to a terminal editor command", "EDITOR_CONFIG");
79
+ return args;
80
+ }
81
+
82
+ function openEntry(entry, options = {}) {
83
+ const file = entryPath(entry.root, entry.relative);
84
+ if (!fs.statSync(file).isFile()) throw new InstallerError("Journal entry is no longer a regular file", "INVALID_ENTRY");
85
+ const env = options.env || process.env;
86
+ const command = env.VISUAL?.trim() || env.EDITOR?.trim() || (process.platform === "win32" ? "notepad" : "vi");
87
+ const [bin, ...args] = editorArgs(command);
88
+ const result = (options.spawnSync || spawnSync)(bin, [...args, file], { stdio: "inherit", cwd: options.cwd, env, shell: false });
89
+ if (result.error) throw new InstallerError(`Cannot start editor ${bin}: ${result.error.message}. Check VISUAL or EDITOR.`, "EDITOR_ERROR");
90
+ if (result.status !== 0) throw new InstallerError(`Editor ${bin} exited with ${result.signal || result.status}.`, "EDITOR_ERROR");
91
+ }
92
+
93
+ function recallEntry(result, options) {
94
+ if (typeof result.path !== "string" || !result.path.startsWith(".journal/work/")) {
95
+ throw new InstallerError("Recall result is not a canonical journal path", "UNSAFE_PATH");
96
+ }
97
+ const relative = result.path.slice(".journal/".length);
98
+ const parts = relative.split("/");
99
+ if (parts[1] !== result.workSlug || path.extname(relative).toLowerCase() !== ".md" ||
100
+ !(parts.length === 3 && parts[2] === "work.md" || parts.length >= 4 && ENTRY_DIRECTORIES.includes(parts[2]))) {
101
+ throw new InstallerError("Recall result is not a journal entry or work file", "UNSAFE_PATH");
102
+ }
103
+ const root = path.resolve(projectContext(path.resolve(options.target), options).journalRoot);
104
+ entryPath(root, relative);
105
+ return { root, relative };
106
+ }
107
+
108
+ module.exports = { listEntries, openEntry, recallEntry };
@@ -0,0 +1,72 @@
1
+ "use strict";
2
+
3
+ const { createPrompt, useState, useKeypress, usePagination } = require("@inquirer/core");
4
+
5
+ function filterFields(workItems = []) {
6
+ const values = (items) => [[undefined, "Any"], ...items.map((value) => [value, value.replaceAll("_", " ")])];
7
+ return [
8
+ { key: "work", label: "Work", values: [[undefined, "All work"], ...workItems.map((work) => [work.slug, work.title])], help: "Restrict results to a work item." },
9
+ { key: "kind", label: "Kind", values: values(["work", "entry"]), help: "Search work descriptions, entries, or both." },
10
+ { key: "type", label: "Entry type", values: values(["plan", "implementation", "status", "manual", "research", "doc", "decision"]), help: "Applies to entries; work descriptions have no entry type." },
11
+ { key: "status", label: "Work status", values: values(["draft", "active", "paused", "completed", "archived"]), help: "Include work items with this status." },
12
+ { key: "visibility", label: "Visibility", values: values(["local_only", "private_synced", "team_shared"]), help: "Restrict results by work visibility." },
13
+ { key: "limit", label: "Result limit", help: "Type a number from 1 to 100, or use Left/Right. Limit is per result kind." },
14
+ ];
15
+ }
16
+
17
+ function filterSummary(filters) {
18
+ const labels = { work: "Work", kind: "Kind", type: "Type", status: "Status", visibility: "Visibility" };
19
+ const scope = Object.entries(labels).filter(([key]) => filters[key])
20
+ .map(([key, label]) => `${label}: ${filters[key]}`);
21
+ return [...(scope.length ? scope : ["All work / all types"]), `Limit: ${filters.limit}`].join(" | ");
22
+ }
23
+
24
+ const filterPrompt = createPrompt((config, done) => {
25
+ const [draft, setDraft] = useState({ ...config.filters });
26
+ const [active, setActive] = useState(0);
27
+ const [digits, setDigits] = useState(null);
28
+ const [error, setError] = useState("");
29
+ const { fields, theme } = config;
30
+ const field = fields[active];
31
+ const validLimit = digits === null || (Number(digits) >= 1 && Number(digits) <= 100);
32
+ useKeypress((key, rl) => {
33
+ rl.clearLine(0);
34
+ if (key.ctrl && key.name === "r") {
35
+ setDraft({ limit: 10 }); setDigits(null); setError("");
36
+ } else if (key.name === "up" || key.name === "down") {
37
+ if (!validLimit) { setError("Enter a limit from 1 to 100."); return; }
38
+ setActive((active + (key.name === "up" ? -1 : 1) + fields.length) % fields.length);
39
+ setDigits(null); setError("");
40
+ } else if (key.name === "left" || key.name === "right") {
41
+ const offset = key.name === "left" ? -1 : 1;
42
+ const next = { ...draft };
43
+ if (field.key === "limit") next.limit = Math.max(1, Math.min(100, draft.limit + offset));
44
+ else {
45
+ const index = Math.max(0, field.values.findIndex(([value]) => value === draft[field.key]));
46
+ const [value] = field.values[(index + offset + field.values.length) % field.values.length];
47
+ if (value === undefined) delete next[field.key]; else next[field.key] = value;
48
+ }
49
+ setDraft(next); setDigits(null); setError("");
50
+ } else if (field.key === "limit" && (/^[0-9]$/.test(key.sequence) || key.name === "backspace")) {
51
+ const text = key.name === "backspace" ? (digits ?? String(draft.limit)).slice(0, -1) : (digits ?? "") + key.sequence;
52
+ setDigits(text); setError(Number(text) < 1 || Number(text) > 100 ? "Limit must be between 1 and 100." : "");
53
+ if (Number(text) >= 1 && Number(text) <= 100) setDraft({ ...draft, limit: Number(text) });
54
+ } else if (key.name === "enter" || key.name === "return") {
55
+ if (!validLimit) setError("Enter a limit from 1 to 100.");
56
+ else done(draft);
57
+ }
58
+ });
59
+ const valueOf = (item) => item.key === "limit" ? (digits ?? String(draft.limit))
60
+ : item.values.find(([value]) => value === draft[item.key])?.[1] || draft[item.key] || "Any";
61
+ const page = usePagination({
62
+ items: fields, active, pageSize: Math.min(fields.length, config.pageSize), loop: true,
63
+ renderItem: ({ item, isActive }) => {
64
+ const text = theme.style.line(`${isActive ? ">" : " "} ${item.label.padEnd(12)} ${isActive ? "< " : " "}${valueOf(item)}${isActive ? " >" : ""}`);
65
+ return isActive ? theme.style.highlight(text) : text;
66
+ },
67
+ });
68
+ return [theme.style.message(config.message).trimEnd(), [page,
69
+ error ? theme.style.detail(`Error: ${error}`) : theme.style.detail(`${valueOf(field)} — ${field.help}`)].join("\n")];
70
+ });
71
+
72
+ module.exports = { filterFields, filterSummary, filterPrompt };
@@ -0,0 +1,87 @@
1
+ "use strict";
2
+
3
+ const { createPrompt, useState, useRef, useEffect, useKeypress, usePagination } = require("@inquirer/core");
4
+
5
+ const DEBOUNCE_MS = 250;
6
+
7
+ // Own the query and result lifecycle so returning from filters or an editor can
8
+ // restore the input, and Enter can never select results for an earlier query.
9
+ const searchPrompt = createPrompt((config, done) => {
10
+ const [query, setQuery] = useState(config.query || "");
11
+ const [result, setResult] = useState({ choices: [], message: "" });
12
+ const [status, setStatus] = useState(query.trim() ? "waiting" : "idle");
13
+ const [error, setError] = useState("");
14
+ const [active, setActive] = useState(0);
15
+ const request = useRef();
16
+ const { theme } = config;
17
+
18
+ useEffect((rl) => { if (config.query) rl.write(config.query); }, []);
19
+ useEffect(() => {
20
+ const controller = new AbortController();
21
+ request.current = controller;
22
+ if (!query.trim()) return () => controller.abort();
23
+ const timer = setTimeout(async () => {
24
+ setStatus("loading");
25
+ try {
26
+ const next = await config.source(query.trim(), { signal: controller.signal });
27
+ if (controller.signal.aborted) return;
28
+ setResult(next);
29
+ setActive(0);
30
+ setStatus("idle");
31
+ } catch (failure) {
32
+ if (controller.signal.aborted) return;
33
+ setResult({ choices: [], message: "" });
34
+ setError(failure.message || String(failure));
35
+ setStatus("idle");
36
+ }
37
+ }, DEBOUNCE_MS);
38
+ return () => { clearTimeout(timer); controller.abort(); };
39
+ }, [query]);
40
+
41
+ const ready = status === "idle";
42
+ const choices = result.choices;
43
+ const selected = ready ? choices[active] : undefined;
44
+ useKeypress((key, rl) => {
45
+ if (key.name === "tab") {
46
+ request.current?.abort();
47
+ done({ value: "filters", query });
48
+ } else if (key.name === "enter" || key.name === "return") {
49
+ if (ready && selected) done({ value: selected.value, query });
50
+ else rl.write(query); // Readline clears its input on Enter.
51
+ } else if (key.name === "up" || key.name === "down") {
52
+ // Readline history navigation must not replace the editable query.
53
+ rl.line = query;
54
+ rl.cursor = query.length;
55
+ if (ready) setActive(Math.max(0, Math.min(choices.length - 1, active + (key.name === "up" ? -1 : 1))));
56
+ } else if (rl.line !== query) {
57
+ // Invalidate synchronously, before a promise or another key can complete.
58
+ request.current?.abort();
59
+ if (!rl.line.trim()) setResult({ choices: [], message: "" });
60
+ setError("");
61
+ setActive(0);
62
+ setStatus(rl.line.trim() ? "waiting" : "idle");
63
+ setQuery(rl.line);
64
+ }
65
+ });
66
+
67
+ const page = usePagination({
68
+ items: choices, active, pageSize: config.pageSize, loop: false,
69
+ renderItem: ({ item, isActive }) => {
70
+ const text = ` ${isActive ? theme.icon.cursor : " "} ${item.name}`;
71
+ return !ready ? theme.style.disabled(text) : isActive ? theme.style.highlight(text) : text;
72
+ },
73
+ });
74
+ const message = !ready ? "Updating results..."
75
+ : result.message || "Type to search the journal.";
76
+ const padded = (text, lines) => [...text.split("\n"), ...Array(lines).fill(" ")].slice(0, lines).join("\n");
77
+ const position = ready && choices.length ? `${active + 1}/${choices.length} ` : "";
78
+ return [
79
+ `${theme.style.message(config.message)} > ${theme.style.answer(query)}`,
80
+ [theme.style.line(config.scope),
81
+ padded(theme.style.detail(error ? `Error: ${error}` : position + message), 2),
82
+ padded(page, config.pageSize),
83
+ padded(selected?.description ? theme.style.detail(selected.description) : " ", 2)].join("\n"),
84
+ ];
85
+ });
86
+
87
+ module.exports = { searchPrompt, DEBOUNCE_MS };
@@ -0,0 +1,142 @@
1
+ "use strict";
2
+
3
+ const { stripVTControlCharacters } = require("node:util");
4
+
5
+ // Two offset journal pages, with a bookmark on the front page.
6
+ const JOURNAL_MARK = [
7
+ " ┌────┬─┐",
8
+ "┌──┤ │ │",
9
+ "│ │ ▾ │",
10
+ "│ └──────┘",
11
+ "└──────┘",
12
+ ];
13
+ const ASCII_MARK = [
14
+ " +----+-+",
15
+ "+--| | |",
16
+ "| | v |",
17
+ "| +------+",
18
+ "+------+",
19
+ ];
20
+
21
+ function wrap(text, width) {
22
+ return String(text).split("\n").flatMap((line) => {
23
+ const lines = [];
24
+ let chars = Array.from(line);
25
+ while (chars.length > width) {
26
+ let end = chars.slice(0, width + 1).lastIndexOf(" ");
27
+ if (end < width / 2) end = width;
28
+ lines.push(chars.slice(0, end).join(""));
29
+ chars = chars.slice(end);
30
+ if (chars[0] === " ") chars.shift();
31
+ }
32
+ return [...lines, chars.join("")];
33
+ }).join("\n");
34
+ }
35
+
36
+ function presentation(output, env = process.env) {
37
+ const color = env.NO_COLOR === undefined && env.TERM !== "dumb" && env.FORCE_COLOR !== "0" &&
38
+ (Boolean(env.FORCE_COLOR) || (output.getColorDepth?.() || 1) >= 4);
39
+ const paint = (code) => (text) => color ? `\x1b[${code}m${text}\x1b[0m` : String(text);
40
+ const accent = paint("36"), bold = paint("1"), muted = paint("2");
41
+ const plainTerminal = env.TERM === "dumb";
42
+ const width = () => Math.max(12, (output.columns || 80) - 4);
43
+ const rows = () => output.rows || 24;
44
+ const indent = (text) => String(text).split("\n").map((line) => ` ${line}`).join("\n");
45
+ const fit = (text) => wrap(stripVTControlCharacters(String(text)), width());
46
+
47
+ const clipped = (text, count) => {
48
+ const lines = fit(text).split("\n");
49
+ if (lines.length > count) lines[count - 1] = lines[count - 1].slice(0, Math.max(0, width() - 3)) + "...";
50
+ return indent(lines.slice(0, count).join("\n"));
51
+ };
52
+
53
+ function banner(compact) {
54
+ if (compact) return `${accent(plainTerminal ? "[=]" : "▤")} ${bold("djournal")}`;
55
+ return (plainTerminal ? ASCII_MARK : JOURNAL_MARK).map((line, index) => accent(line) +
56
+ (index === 2 ? ` ${bold("djournal")}` : "")).join("\n");
57
+ }
58
+
59
+ function frame(header, messages, type, question = "", choices = []) {
60
+ const context = messages.join("\n").trim();
61
+ const contextLines = context ? fit(context).split("\n").length + 1 : 0;
62
+ const lines = [];
63
+ if (typeof header === "object" && header) {
64
+ const compact = type === "search" || type === "filters" || width() < 32 || rows() < 24 || contextLines >= 4;
65
+ lines.push(indent(banner(compact)));
66
+ lines.push(type === "search" || type === "filters" ? clipped(`Project: ${header.project}`, 1) : indent(fit(`Project: ${header.project}`)));
67
+ } else if (header) lines.push(indent(fit(header)));
68
+ lines.push(indent(muted("-".repeat(Math.min(60, width())))));
69
+ const controls = type === "checkbox"
70
+ ? "Up/Down move Space toggle Enter continue"
71
+ : type === "search" ? "Up/Down select Enter open Tab filters"
72
+ : type === "filters" ? "Up/Down field Left/Right change"
73
+ : type === "select" ? "Up/Down move Enter select" : "Enter accept";
74
+ const navigation = type === "search"
75
+ ? "Up/Down select Enter open\nTab filters Esc back Ctrl-C exit"
76
+ : type === "filters"
77
+ ? `${controls}\nEnter apply Esc discard\nCtrl-R reset Ctrl-C exit`
78
+ : `${controls} Esc back Ctrl-C exit`;
79
+ const hints = type === "search" || type === "filters" || navigation.length <= width() ? navigation : `${controls}\nEsc back Ctrl-C exit`;
80
+ lines.push(indent(muted(fit(hints))), "");
81
+ if (context) {
82
+ for (const line of fit(context).split("\n")) {
83
+ const style = /^(?:[A-Z_]+:|fail\b)/.test(line) ? paint("31") : /^ok\b|^Configuration saved/.test(line) ? paint("32") : (text) => text;
84
+ lines.push(indent(style(line)));
85
+ }
86
+ lines.push("");
87
+ }
88
+ const text = lines.join("\n") + "\n";
89
+ const used = text.split("\n").length + fit(question).split("\n").length;
90
+ const descriptionLines = Math.max(1, ...choices.map((choice) => choice.description ? fit(choice.description).split("\n").length : 0));
91
+ if (type === "search" || type === "filters") return { text, pageSize: Math.max(1, Math.min(8, rows() - used - (type === "search" ? 6 : 4))) };
92
+ return { text, pageSize: Math.max(3, Math.min(10, rows() - used - descriptionLines - 3)) };
93
+ }
94
+
95
+ function choices(items) {
96
+ return items.map(([value, label, detail]) => {
97
+ const full = stripVTControlCharacters(String(label));
98
+ const limit = width() - 2;
99
+ const long = Array.from(full).length > limit;
100
+ return {
101
+ value,
102
+ name: long ? Array.from(full).slice(0, limit - 3).join("") + "..." : full,
103
+ description: [long ? full : "", detail].filter(Boolean).join("\n") || undefined,
104
+ };
105
+ });
106
+ }
107
+
108
+ const theme = {
109
+ prefix: { idle: "", done: "" },
110
+ icon: { cursor: ">", checked: "[x]", unchecked: "[ ]" },
111
+ helpMode: "never",
112
+ style: {
113
+ message: (text) => indent(bold(fit(text))) + "\n",
114
+ highlight: (text) => accent(bold(text)),
115
+ answer: accent,
116
+ description: (text) => indent(muted(fit(text))),
117
+ line: (text) => clipped(text, 1),
118
+ detail: (text) => muted(clipped(text, 2)),
119
+ error: (text) => indent(paint("31")(fit(`Error: ${text}`))),
120
+ defaultAnswer: (text) => muted(`(${text})`),
121
+ help: muted,
122
+ key: bold,
123
+ disabled: muted,
124
+ disabledChoice: muted,
125
+ keysHelpTip: () => "",
126
+ },
127
+ };
128
+ return {
129
+ frame, choices,
130
+ theme: (type) => ({
131
+ ...theme,
132
+ style: {
133
+ ...theme.style,
134
+ message: (text) => type === "input" || type === "confirm"
135
+ ? ` ${bold(fit(text))}\n >`
136
+ : theme.style.message(text),
137
+ },
138
+ }),
139
+ };
140
+ }
141
+
142
+ module.exports = { presentation };
package/lib/setup.js ADDED
@@ -0,0 +1,396 @@
1
+ "use strict";
2
+
3
+ const path = require("node:path");
4
+ const installer = require("./installer/index.js");
5
+ const entries = require("./setup-entries.js");
6
+ const recall = require("./recall/index.js");
7
+ const { filterFields, filterSummary } = require("./setup-filters.js");
8
+ const { presentation } = require("./setup-style.js");
9
+
10
+ class Cancelled extends Error {}
11
+ class Back extends Error {}
12
+
13
+ // Keep the flow independent of the prompt library so operations remain testable.
14
+ function terminal(input = process.stdin, output = process.stdout, env = process.env) {
15
+ if (!input.isTTY || !output.isTTY) {
16
+ throw new installer.InstallerError("The wizard requires an interactive terminal; use djournal --help for commands, or djournal status --json for automation", "INTERACTIVE_REQUIRED");
17
+ }
18
+ const prompts = { ...require("@inquirer/prompts"), search: require("./setup-search.js").searchPrompt, filters: require("./setup-filters.js").filterPrompt };
19
+ const style = presentation(output, env);
20
+ const clearScreen = "\x1b[2J\x1b[H";
21
+ let header = "";
22
+ let messages = [];
23
+ function frame(type, question, choices) {
24
+ output.write(clearScreen);
25
+ const layout = style.frame(header, messages, type, question, choices);
26
+ output.write(layout.text);
27
+ messages = [];
28
+ return layout;
29
+ }
30
+ const controller = new AbortController();
31
+ let activePrompt;
32
+ const cancel = () => controller.abort();
33
+ const onKey = (_value, key) => {
34
+ if (key?.ctrl && key.name === "d") cancel();
35
+ else if (key?.name === "escape") activePrompt?.abort(new Back());
36
+ };
37
+ input.on("end", cancel);
38
+ input.on("close", cancel);
39
+ input.on("keypress", onKey);
40
+ if (input.readableEnded || input.destroyed) cancel();
41
+ async function prompt(type, config) {
42
+ if (controller.signal.aborted) throw new Cancelled();
43
+ const layout = frame(type, config.message, config.choices);
44
+ const current = new AbortController();
45
+ activePrompt = current;
46
+ const abort = () => current.abort();
47
+ controller.signal.addEventListener("abort", abort, { once: true });
48
+ try { return await prompts[type]({ ...config, pageSize: layout.pageSize, theme: style.theme(type) }, {
49
+ input, output, signal: current.signal, clearPromptOnDone: true,
50
+ }); }
51
+ catch (error) {
52
+ if (current.signal.reason instanceof Back && !controller.signal.aborted) throw current.signal.reason;
53
+ if (["ExitPromptError", "AbortPromptError"].includes(error.name) || controller.signal.aborted) throw new Cancelled();
54
+ throw error;
55
+ } finally {
56
+ controller.signal.removeEventListener("abort", abort);
57
+ activePrompt = undefined;
58
+ }
59
+ }
60
+ const choicesFor = style.choices;
61
+ return {
62
+ header: (message) => { header = message; },
63
+ // Messages belong to the next frame, so clearing never hides a new result.
64
+ write: (message) => { messages.push(message); },
65
+ choose: (message, choices, defaultValue) => prompt("select", {
66
+ message, choices: choicesFor(choices), default: defaultValue, pageSize: 10, loop: false,
67
+ }),
68
+ search: (message, source, { query = "", scope = "All work / all types" } = {}) => prompt("search", {
69
+ message, query, scope,
70
+ source: async (term, context) => {
71
+ const result = await source(term, context);
72
+ return { ...result, choices: choicesFor(result.choices) };
73
+ },
74
+ }),
75
+ filters: (filters, fields) => prompt("filters", { message: "Search filters", filters, fields }),
76
+ multiple: (message, choices, defaults = []) => prompt("checkbox", {
77
+ message,
78
+ choices: choicesFor(choices).map((choice) => ({ ...choice, checked: defaults.includes(choice.value) })),
79
+ pageSize: 10, loop: false,
80
+ }),
81
+ text: async (message, defaultValue = "", validate = () => true) => {
82
+ const answer = await prompt("input", {
83
+ message, default: defaultValue,
84
+ validate: (value) => (value.trim() && validate(value.trim())) || "Enter a valid value.",
85
+ });
86
+ return answer.trim();
87
+ },
88
+ confirm: (message, defaultValue = false) => prompt("confirm", { message, default: defaultValue }),
89
+ external: async (operation) => {
90
+ output.write(clearScreen);
91
+ const raw = input.isRaw;
92
+ const flowing = input.readableFlowing;
93
+ input.removeListener("keypress", onKey);
94
+ input.pause();
95
+ if (input.isTTY && input.setRawMode) input.setRawMode(false);
96
+ try { return await operation(); }
97
+ finally {
98
+ if (input.isTTY && input.setRawMode) input.setRawMode(!!raw);
99
+ input.on("keypress", onKey);
100
+ if (flowing) input.resume();
101
+ }
102
+ },
103
+ close: () => {
104
+ cancel();
105
+ input.removeListener("end", cancel);
106
+ input.removeListener("close", cancel);
107
+ input.removeListener("keypress", onKey);
108
+ output.write(clearScreen);
109
+ if (messages.length) output.write(`${messages.join("\n")}\n`);
110
+ messages = [];
111
+ },
112
+ };
113
+ }
114
+
115
+ async function setup(options, dependencies = {}) {
116
+ const ui = dependencies.ui || terminal();
117
+ const api = { ...installer, ...entries, ...recall, ...dependencies.api };
118
+ const print = dependencies.print || ((result) => ui.write(JSON.stringify(result, null, 2)));
119
+ const base = { target: path.resolve(options.target || process.cwd()), sourceRoot: options.sourceRoot, interactive: false };
120
+ let failed = false;
121
+ async function menu(message, choices) {
122
+ try { return await ui.choose(message, choices); }
123
+ catch (error) { if (error instanceof Back) return "back"; throw error; }
124
+ }
125
+ async function backToMenu(operation) {
126
+ try { return await operation(); }
127
+ catch (error) { if (error instanceof Back) return false; throw error; }
128
+ }
129
+ async function run(name, extra = {}) {
130
+ const result = await api[name]({ ...base, ...extra });
131
+ print(result, false, { write: (text) => ui.write(text.replace(/\n$/, "")) });
132
+ if (result.ok === false || result.clean === false || result.installed === false || result.conflicts?.length) failed = true;
133
+ return result;
134
+ }
135
+
136
+ const configuration = () => backToMenu(configureProject);
137
+ async function configureProject() {
138
+ const { config } = await api.configure(base);
139
+ const changes = [];
140
+ ui.write("\nConfigure this project. Enter keeps the displayed setting; nothing is saved until you confirm.");
141
+ const mode = await ui.choose("Where should selected work items be shared?", [
142
+ ["local", "Keep work local", "Disable synchronization for this project."],
143
+ ["colocated", "Use this project's Git repository", "Share selected work through this project's journal projection."],
144
+ ["standalone", "Use a separate Git repository", "Keep shared journal history in an existing journal repository."],
145
+ ["back", "Back"],
146
+ ], config.sync?.enabled ? config.sync.mode : "local");
147
+ if (mode === "back") return false;
148
+ if (mode === "local") changes.push(["sync.enabled", "false"]);
149
+ else {
150
+ changes.push(["sync.mode", mode]);
151
+ const location = mode === "colocated" ? base.target : path.resolve(base.target, await ui.text(
152
+ "Path to the existing journal Git repository",
153
+ config.sync?.mode === "standalone" ? config.sync.path : "",
154
+ ));
155
+ changes.push(["sync.path", location]);
156
+ const auto = mode === "standalone" && await ui.confirm(
157
+ "Automatically sync shared work after journal closure (may commit and push)?",
158
+ config.sync?.mode === "standalone" && !!config.sync.auto,
159
+ );
160
+ changes.push(["sync.auto", String(auto)], ["sync.enabled", "true"]);
161
+ ui.write("Sharing is opt-in per work item. Use List to select work to share.");
162
+ }
163
+ const updates = await ui.confirm("Check periodically for djournal updates?", config.updates?.enabled !== false);
164
+ changes.push(["updates.enabled", String(updates)]);
165
+ if (updates) {
166
+ const interval = await ui.text("Hours between update checks", String(config.updates?.intervalHours || 24),
167
+ (value) => Number.isFinite(Number(value)) && Number(value) > 0);
168
+ changes.push(["updates.intervalHours", String(Number(interval))]);
169
+ }
170
+ const pending = changes.filter(([key, value]) => {
171
+ const current = key.split(".").reduce((object, part) => object?.[part], config);
172
+ return String(current) !== value;
173
+ });
174
+ if (!pending.length) { ui.write("Configuration is already up to date."); return true; }
175
+ ui.write(`\nConfiguration changes for ${base.target}:`);
176
+ for (const [key, value] of pending) ui.write(` ${key}: ${value}`);
177
+ if (!await ui.confirm("Save these settings?")) return false;
178
+ for (const [key, value] of pending) await api.configure({ ...base, key, value });
179
+ ui.write("Configuration saved.");
180
+ return true;
181
+ }
182
+
183
+ async function installation() {
184
+ const detected = api.detectHarnesses(base.target);
185
+ ui.write(`\nDetected integrations: ${detected.supported.join(", ") || "none"}.`);
186
+ const choice = await ui.choose("Which coding-agent integrations should be installed?", [
187
+ ...installer.SUPPORTED_HARNESSES.map((name) => [name, name]),
188
+ ["all", "All supported integrations"],
189
+ ["custom", "Choose multiple integrations"],
190
+ ["instructions", "Instructions only (no hooks)"],
191
+ ["back", "Back"],
192
+ ]);
193
+ if (choice === "back") return;
194
+ let harnesses = [];
195
+ if (choice === "custom") {
196
+ harnesses = await ui.multiple("Choose integrations (Space to toggle, Enter to continue)",
197
+ installer.SUPPORTED_HARNESSES.map((name) => [name, name]), detected.supported);
198
+ } else if (choice === "all") harnesses = [...installer.SUPPORTED_HARNESSES];
199
+ else if (choice !== "instructions") harnesses = [choice];
200
+ ui.write("Existing integrations are retained when installing into an installed project.");
201
+ if (!await ui.confirm(`Install ${harnesses.join(", ") || "instructions only"} in ${base.target}?`)) return;
202
+ await run("install", { harnesses, instructionsOnly: !harnesses.length });
203
+ await configuration();
204
+ }
205
+
206
+ async function workItems() {
207
+ while (true) {
208
+ let result;
209
+ try { result = await api.listWork(base); }
210
+ catch (error) {
211
+ if (error.code !== "NO_ACTIVE_WORK") throw error;
212
+ ui.write("No work items yet. Ask your coding agent to start a new work item with init-work.");
213
+ return;
214
+ }
215
+ const selected = await menu("Choose a work item", [
216
+ ...result.workItems.map((item) => [item.slug, `${item.title} [${item.status}]${item.selected ? " *" : ""}`,
217
+ `${item.slug}\nVisibility: ${item.visibility || "unknown"}${item.selected ? " | Selected work" : ""}`]),
218
+ ["back", "Back"],
219
+ ]);
220
+ if (selected === "back") return;
221
+ const item = result.workItems.find((candidate) => candidate.slug === selected);
222
+ while (true) {
223
+ ui.write(`\n${item.title}\n${item.slug}\nStatus: ${item.status}; visibility: ${item.visibility}`);
224
+ const action = await menu("What would you like to do with this work item?", [
225
+ ["entries", "Open entry in editor", "Browse this work's journal, research, docs, and decisions."],
226
+ ["share", "Share", "Mark this work for Git synchronization."],
227
+ ["pull", "Pull", "Import changes from the journal projection."],
228
+ ["sync", "Sync", "Import and export shared work."],
229
+ ...(item.status === "active" ? [["bindWork", "Bind to a session", "Select this work for an agent session."]] : []),
230
+ ["back", "Back to work items"],
231
+ ]);
232
+ if (action === "back") break;
233
+ if (action === "entries") { await browseEntries(item); continue; }
234
+ await backToMenu(async () => {
235
+ if (action === "bindWork") {
236
+ const session = await ui.text("Agent session ID", process.env.DJOURNAL_SESSION_ID || "");
237
+ if (await ui.confirm(`Bind ${item.slug} to this session?`)) await run(action, { work: item.slug, session });
238
+ return;
239
+ }
240
+ const { config } = await api.configure(base);
241
+ if (!config.sync?.enabled) {
242
+ ui.write("Synchronization is disabled for this project.");
243
+ if (!await ui.confirm("Configure synchronization now?")) return;
244
+ await configuration();
245
+ const updated = await api.configure(base);
246
+ if (!updated.config.sync?.enabled) return;
247
+ }
248
+ const warning = action === "sync" ? " This may commit and push in standalone mode." : "";
249
+ if (!await ui.confirm(`${action} ${item.slug}?${warning}`)) return;
250
+ await run(action, { work: item.slug });
251
+ if (action === "share") ui.write("Work marked for sharing. Use Sync to copy it to the Git projection.");
252
+ });
253
+ }
254
+ }
255
+ }
256
+
257
+ async function browseEntries(item) {
258
+ while (true) {
259
+ const records = await api.listEntries({ ...base, work: item.slug });
260
+ if (!records.length) { ui.write("No journal entries yet for this work item."); return; }
261
+ const selected = await menu("Open an entry (close the editor to return)", [
262
+ ...records.map((entry) => [entry.relative, entry.title,
263
+ `${entry.date?.slice(0, 10) || "Undated"} | ${entry.entryType}\n${entry.relative.split("/").slice(2).join("/")}`]),
264
+ ["back", "Back to work item"],
265
+ ]);
266
+ if (selected === "back") return;
267
+ const entry = records.find((record) => record.relative === selected);
268
+ await openInEditor(() => entry);
269
+ }
270
+ }
271
+
272
+ async function openInEditor(resolveEntry) {
273
+ try {
274
+ const entry = await resolveEntry();
275
+ const open = () => api.openEntry(entry, { cwd: base.target });
276
+ if (ui.external) await ui.external(open);
277
+ else await open();
278
+ } catch (error) {
279
+ if (error instanceof Cancelled) throw error;
280
+ failed = true;
281
+ ui.write(`${error.code || "EDITOR_ERROR"}: ${error.message}`);
282
+ }
283
+ }
284
+
285
+ async function recallMenu() {
286
+ let filters = { limit: 10 };
287
+ async function editFilters() {
288
+ let workItems = [];
289
+ try { ({ workItems } = await api.listWork(base)); }
290
+ catch (error) { if (error.code !== "NO_ACTIVE_WORK") throw error; }
291
+ filters = await ui.filters(filters, filterFields(workItems));
292
+ }
293
+ async function search() {
294
+ let query = "";
295
+ while (true) {
296
+ const selected = await ui.search("Search journal", async (term, { signal }) => {
297
+ let result;
298
+ try { result = await api.searchRecall(term, { ...base, ...filters }); }
299
+ catch (error) { if (!signal.aborted) failed = true; throw error; }
300
+ const matches = [...result.workItems, ...result.entries].sort((a, b) => b.score - a.score);
301
+ const message = [matches.length ? `${matches.length} results (up to ${filters.limit} per kind).` : "No matches. Edit query or Tab for filters."];
302
+ for (const warning of (result.warnings || []).slice(0, 3)) message.push(`Warning: ${warning.code}${warning.path ? ` - ${warning.path}` : ""}`);
303
+ if (result.warnings?.length > 3) message.push(`${result.warnings.length - 3} more warnings; use djournal recall index --json for details.`);
304
+ return {
305
+ choices: matches.map((item) => [item, item.title, [item.entryType, item.summary, item.path].filter(Boolean).join("\n")]),
306
+ message: message.filter(Boolean).join("\n"),
307
+ };
308
+ }, { query, scope: filterSummary(filters) });
309
+ query = selected.query;
310
+ if (selected.value === "back") return;
311
+ if (selected.value === "filters") await backToMenu(editFilters);
312
+ else await openInEditor(() => api.recallEntry(selected.value, base));
313
+ }
314
+ }
315
+
316
+ while (true) {
317
+ const action = await menu("Recall", [
318
+ ["search", "Search journal", "Find entries and work items, then open their canonical Markdown."],
319
+ ["index", "Refresh index", "Update the search cache from the current journal."],
320
+ ["rebuild", "Rebuild index", "Recreate the disposable search cache. Journal entries are kept."],
321
+ ["back", "Back"],
322
+ ]);
323
+ if (action === "back") return;
324
+ await backToMenu(async () => {
325
+ if (action === "search") await search();
326
+ else if (action === "index" || await ui.confirm("Rebuild the recall index?")) {
327
+ await run("buildRecallIndex", { rebuild: action === "rebuild" });
328
+ }
329
+ });
330
+ }
331
+ }
332
+
333
+ async function uninstallation() {
334
+ const manifest = await api.loadManifest(base.target);
335
+ if (!manifest) throw new installer.InstallerError("djournal is not installed in this project", "NOT_INSTALLED");
336
+ const choice = await menu("Remove which integrations?", [
337
+ ["all", "All integrations and installed assets"],
338
+ ...manifest.harnesses.map((name) => [name, name]), ["back", "Back"],
339
+ ]);
340
+ if (choice === "back") return;
341
+ ui.write("Journal entries are kept. Modified installed files are preserved and reported as conflicts.");
342
+ if (await ui.confirm(`Uninstall ${choice === "all" ? "all integrations" : choice} from ${base.target}?`)) {
343
+ await run("uninstall", choice === "all" ? { all: true } : { harnesses: [choice] });
344
+ }
345
+ }
346
+
347
+ try {
348
+ const heading = `djournal\nProject: ${base.target}\nUse ↑/↓ to navigate and Enter to select. Esc goes back; Ctrl-C exits. Completed actions are kept.`;
349
+ if (ui.header) ui.header({ project: base.target });
350
+ else ui.write(heading);
351
+ while (true) {
352
+ const action = await menu("What would you like to do?", [
353
+ ["list", "List", "Browse work items, open entries, and manage sharing."],
354
+ ["recall", "Recall", "Search journal knowledge and manage its search index."],
355
+ ["status", "Status", "View installation, integration, and version status."],
356
+ ["install", "Install", "Add djournal integrations and configure this project."],
357
+ ["configure", "Configure", "Set sharing and update preferences."],
358
+ ["upgrade", "Upgrade", "Refresh this project's installed journal assets."],
359
+ ["update", "Update", "Check for a newer CLI release."],
360
+ ["doctor", "Doctor", "Check this project's journal installation."],
361
+ ["uninstall", "Uninstall", "Remove installed integrations while keeping journal history."],
362
+ ["exit", "Exit", "Return to your shell. Completed actions are kept."],
363
+ ]);
364
+ if (action === "exit") return { failed };
365
+ if (action === "back") continue;
366
+ try {
367
+ if (action === "list") await workItems();
368
+ else if (action === "recall") await recallMenu();
369
+ else if (action === "status") await run("status");
370
+ else if (action === "uninstall") await uninstallation();
371
+ else if (action === "install") await installation();
372
+ else if (action === "configure") await configuration();
373
+ else if (action === "upgrade") {
374
+ if (await ui.confirm(`Upgrade installed assets in ${base.target}?`)) await run("upgrade");
375
+ } else if (action === "update") {
376
+ const result = await run("checkUpdates");
377
+ if (result.updateAvailable) ui.write("To update the CLI, run: npm install -g djournal@latest\nThen use Upgrade to refresh this project's assets.");
378
+ } else if (action === "doctor") await run("doctor");
379
+ } catch (error) {
380
+ if (error instanceof Back) continue;
381
+ if (error instanceof Cancelled) throw error;
382
+ failed = true;
383
+ ui.write(`${error.code || "ERROR"}: ${error.message}`);
384
+ if (error.code === "NOT_INSTALLED") ui.write("Choose Install from the main menu to initialize this project.");
385
+ }
386
+ }
387
+ } catch (error) {
388
+ if (!(error instanceof Cancelled)) throw error;
389
+ ui.write("\nWizard cancelled. Completed actions have been kept.");
390
+ return { cancelled: true, failed };
391
+ } finally {
392
+ ui.close();
393
+ }
394
+ }
395
+
396
+ module.exports = { Back, Cancelled, setup, terminal };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "djournal",
3
- "version": "0.11.0",
3
+ "version": "0.12.0",
4
4
  "description": "Durable project memory for coding agents, stored as linked Markdown",
5
5
  "type": "commonjs",
6
6
  "bin": {
@@ -29,7 +29,7 @@
29
29
  "benchmark:recall": "node scripts/benchmark-recall.cjs",
30
30
  "link:global": "npm link",
31
31
  "release": "semantic-release",
32
- "test": "node tests/update-checker.test.js && node tests/journal-hook.test.js && node tests/pi-adapter.test.js && node tests/recall.test.js && node tests/recall-files.test.js && node tests/installer/installer.test.js && node tests/release-policy.test.js && node tests/skill-instructions.test.js && npm run check:package",
32
+ "test": "node tests/setup.test.js && node tests/update-checker.test.js && node tests/journal-hook.test.js && node tests/pi-adapter.test.js && node tests/recall.test.js && node tests/recall-files.test.js && node tests/installer/installer.test.js && node tests/release-policy.test.js && node tests/skill-instructions.test.js && npm run check:package",
33
33
  "prepublishOnly": "npm test"
34
34
  },
35
35
  "repository": {
@@ -59,6 +59,8 @@
59
59
  "semantic-release": "25.0.3"
60
60
  },
61
61
  "dependencies": {
62
+ "@inquirer/core": "10.3.2",
63
+ "@inquirer/prompts": "7.10.1",
62
64
  "minisearch": "7.2.0",
63
65
  "semver": "7.8.5",
64
66
  "yaml": "2.9.0"