djournal 0.6.0 → 0.7.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.
@@ -97,6 +97,18 @@ function shouldAutoSync(root) {
97
97
  return config.enabled === true && config.auto === true && config.mode === "standalone";
98
98
  }
99
99
 
100
+ function environmentFlag(value) {
101
+ return typeof value === "string" ? !["", "0", "false"].includes(value.toLowerCase()) : Boolean(value);
102
+ }
103
+
104
+ function shouldCheckUpdates(root, env = process.env, options = {}) {
105
+ const config = readConfig(projectContext(root));
106
+ if (config.updates?.enabled === false) return false;
107
+ if (environmentFlag(env.NO_UPDATE_NOTIFIER) || environmentFlag(env.CI)) return false;
108
+ if (!options.allowTest && (env.NODE_ENV === "test" || environmentFlag(env.NODE_TEST_CONTEXT))) return false;
109
+ return true;
110
+ }
111
+
100
112
  function context(event, message) {
101
113
  return {
102
114
  hookSpecificOutput: {
@@ -173,6 +185,34 @@ function runJournal(root, args, runner) {
173
185
  return { ok: true, message: (result.stdout || "").trim() };
174
186
  }
175
187
 
188
+ function runUpdateCheck(root, runner) {
189
+ const run = runner || ((command, args, options) => spawnSync(command, args, options));
190
+ const result = run("journal", ["update", "check", "--passive", "--json"], {
191
+ cwd: root,
192
+ encoding: "utf8",
193
+ timeout: 5000,
194
+ });
195
+ if (result.error || result.status !== 0) return null;
196
+ try {
197
+ const value = JSON.parse(result.stdout || "");
198
+ return value && typeof value === "object" && value.enabled !== false ? value : null;
199
+ } catch {
200
+ return null;
201
+ }
202
+ }
203
+
204
+ function updateNotice(value) {
205
+ if (!value) return "";
206
+ const messages = [];
207
+ if (value.updateAvailable && value.cliVersion && value.latestVersion) {
208
+ messages.push(`djournal ${value.latestVersion} is available (CLI ${value.cliVersion}). Update the npm package, then run \`djournal upgrade\` in this project.`);
209
+ }
210
+ if (value.projectUpdateAvailable && value.projectVersion && value.cliVersion) {
211
+ messages.push(`This project uses djournal assets ${value.projectVersion}; CLI ${value.cliVersion} is installed. Run \`djournal upgrade\`.`);
212
+ }
213
+ return messages.length ? ` ${messages.join(" ")}` : "";
214
+ }
215
+
176
216
  function requestsJournalSync(prompt) {
177
217
  const match = prompt.match(/\b(?:sync|synchronize|pull)\s+(?:the\s+)?journal\b|\bjournal\s+(?:sync|synchronize|pull)\b/i);
178
218
  if (!match) return false;
@@ -193,9 +233,14 @@ function handle(payload, options = {}) {
193
233
  ? " Journal pull completed before loading active work."
194
234
  : ` Automatic journal pull failed: ${result.message}`;
195
235
  }
236
+ const env = options.env || process.env;
237
+ const allowTest = typeof options.updateRunner === "function";
238
+ const updateMessage = shouldCheckUpdates(root, env, { allowTest })
239
+ ? updateNotice(runUpdateCheck(root, options.updateRunner))
240
+ : "";
196
241
  const work = activeWork(root);
197
242
  const suffix = work ? ` Active work: ${work.slug}.` : " No valid active work is selected.";
198
- return context(event, `Follow AGENTS.md and .agents/rules/AUTOMATION.md.${pullMessage}${suffix}`);
243
+ return context(event, `Follow AGENTS.md and .agents/rules/AUTOMATION.md.${pullMessage}${updateMessage}${suffix}`);
199
244
  }
200
245
 
201
246
  if (event === "UserPromptSubmit") {
@@ -263,4 +308,13 @@ if (require.main === module) {
263
308
  main();
264
309
  }
265
310
 
266
- module.exports = { handle, parseFrontmatter, requestsJournalSync, resolveClosedEntry, shouldAutoSync };
311
+ module.exports = {
312
+ handle,
313
+ parseFrontmatter,
314
+ requestsJournalSync,
315
+ resolveClosedEntry,
316
+ runUpdateCheck,
317
+ shouldAutoSync,
318
+ shouldCheckUpdates,
319
+ updateNotice,
320
+ };
package/README.md CHANGED
@@ -214,6 +214,7 @@ global store referenced by `.djournal.json`.
214
214
  ```bash
215
215
  djournal status
216
216
  djournal doctor
217
+ djournal update check
217
218
  djournal config sync.enabled true
218
219
  djournal share --all
219
220
  djournal share
@@ -237,6 +238,12 @@ three-way reconciliation. `sync` pulls first, then projects and publishes
237
238
  shared work. Colocated mode leaves product-repository Git operations to the
238
239
  user; standalone mode performs the configured Git pull and push.
239
240
 
241
+ At session start, djournal reads a user-local npm release cache and reports a
242
+ known CLI or project-asset update every session until it is installed. Stale
243
+ release data is refreshed in the background at most once every 24 hours. Run
244
+ `djournal update check` for an immediate check, or disable passive checks with
245
+ `djournal config updates.enabled false` or `NO_UPDATE_NOTIFIER=1`.
246
+
240
247
  ## Status
241
248
 
242
249
  Codex, Claude Code, and Pi are supported. OpenCode and Zed adapters are planned.
@@ -258,6 +265,7 @@ djournal is licensed under the [Apache License 2.0](LICENSE).
258
265
 
259
266
  - [Installation and repository layouts](docs/installation.md)
260
267
  - [Remote Git sync setup](docs/remote-sync.md)
268
+ - [Read-only team journal access](docs/read-only-team-journal.md)
261
269
  - [Architecture and data model](docs/architecture.md)
262
270
  - [Visibility and sharing](docs/visibility-and-sharing.md)
263
271
  - [Djournal in practice](docs/djournal-in-practice.md)
package/bin/journal.js CHANGED
@@ -3,8 +3,10 @@
3
3
  "use strict";
4
4
 
5
5
  const path = require("node:path");
6
+ const { spawn } = require("node:child_process");
6
7
  const {
7
8
  InstallerError,
9
+ checkUpdates,
8
10
  configure,
9
11
  doctor,
10
12
  install,
@@ -29,6 +31,7 @@ function usage() {
29
31
  journal share [--target DIR] [--work SLUG | --all] [--dry-run] [--json]
30
32
  journal pull [--target DIR] [--work SLUG] [--dry-run] [--json]
31
33
  journal sync [--target DIR] [--work SLUG] [--dry-run] [--json]
34
+ journal update check [--target DIR] [--json]
32
35
 
33
36
  Options:
34
37
  --dry-run Show the planned operation without writing
@@ -44,10 +47,14 @@ Options:
44
47
  function parseArgs(argv) {
45
48
  const args = [...argv];
46
49
  const command = args.shift();
47
- if (!command || !["install", "upgrade", "uninstall", "status", "doctor", "config", "share", "pull", "sync"].includes(command)) {
50
+ if (!command || !["install", "upgrade", "uninstall", "status", "doctor", "config", "share", "pull", "sync", "update"].includes(command)) {
48
51
  throw new InstallerError(usage(), "USAGE");
49
52
  }
50
53
  const options = { command, harnesses: [] };
54
+ if (command === "update") {
55
+ options.subcommand = args.shift();
56
+ if (options.subcommand !== "check") throw new InstallerError("update requires the check subcommand", "USAGE");
57
+ }
51
58
  while (args.length) {
52
59
  const arg = args.shift();
53
60
  if (arg === "--target") {
@@ -68,6 +75,8 @@ function parseArgs(argv) {
68
75
  else if (arg === "--auto") options.auto = true;
69
76
  else if (arg === "--yes") options.yes = true;
70
77
  else if (arg === "--json") options.json = true;
78
+ else if (arg === "--passive" && command === "update") options.passive = true;
79
+ else if (arg === "--refresh-cache" && command === "update") options.refreshCache = true;
71
80
  else if (arg === "--help" || arg === "-h") throw new InstallerError(usage(), "HELP");
72
81
  else if (command === "config" && !options.key) options.key = arg;
73
82
  else if (command === "config" && typeof options.value === "undefined") options.value = arg;
@@ -92,12 +101,27 @@ function print(value, json) {
92
101
  process.stdout.write(`${JSON.stringify(value, null, 2)}\n`);
93
102
  return;
94
103
  }
104
+ if (value.action === "update-check") {
105
+ process.stdout.write(`cli version: ${value.cliVersion || "unknown"}\n`);
106
+ if (value.projectVersion) process.stdout.write(`project assets: ${value.projectVersion}\n`);
107
+ process.stdout.write(`latest version: ${value.latestVersion || "unknown"}\n`);
108
+ if (value.updateAvailable) process.stdout.write(`update available: ${value.cliVersion} -> ${value.latestVersion}\n`);
109
+ else if (value.latestVersion) process.stdout.write("djournal CLI is up to date\n");
110
+ if (value.projectUpdateAvailable) process.stdout.write(`project upgrade available: ${value.projectVersion} -> ${value.cliVersion}\n`);
111
+ if (value.checkedAt) process.stdout.write(`checked: ${value.checkedAt}\n`);
112
+ return;
113
+ }
95
114
  if (value.action) process.stdout.write(`${value.action}: ${value.target}\n`);
96
115
  else if (typeof value.installed === "boolean") process.stdout.write(value.installed ? `installed: ${value.target}\n` : `not installed: ${value.target}\n`);
97
116
  else process.stdout.write(`${value.ok ? "ok" : "failed"}: ${value.target}\n`);
98
117
  if (value.harnesses) process.stdout.write(`harnesses: ${value.harnesses.join(", ") || "instructions-only"}\n`);
99
118
  if (value.key) process.stdout.write(`${value.key}: ${JSON.stringify(value.value)}\n`);
100
119
  else if (value.config) process.stdout.write(`${JSON.stringify(value.config, null, 2)}\n`);
120
+ if (value.cliVersion) process.stdout.write(`cli version: ${value.cliVersion}\n`);
121
+ if (value.projectVersion) process.stdout.write(`project assets: ${value.projectVersion}\n`);
122
+ if (value.latestVersion) process.stdout.write(`latest version: ${value.latestVersion}\n`);
123
+ if (value.updateAvailable) process.stdout.write("update available: yes\n");
124
+ if (value.projectUpdateAvailable) process.stdout.write("project upgrade available: yes\n");
101
125
  if (value.workItems) {
102
126
  for (const item of value.workItems) {
103
127
  process.stdout.write(`${item.changed ? "shared" : "unchanged"} ${item.work}\n`);
@@ -124,6 +148,28 @@ function exitCodeFor(code) {
124
148
  return 1;
125
149
  }
126
150
 
151
+ function launchUpdateRefresh(options, runner = spawn) {
152
+ try {
153
+ const child = runner(process.execPath, [
154
+ __filename,
155
+ "update",
156
+ "check",
157
+ "--refresh-cache",
158
+ "--json",
159
+ "--target",
160
+ options.target,
161
+ ], {
162
+ detached: true,
163
+ stdio: "ignore",
164
+ env: { ...process.env, DJOURNAL_UPDATE_WORKER: "1" },
165
+ });
166
+ child.unref();
167
+ return true;
168
+ } catch {
169
+ return false;
170
+ }
171
+ }
172
+
127
173
  async function main() {
128
174
  try {
129
175
  const options = parseArgs(process.argv.slice(2));
@@ -136,6 +182,10 @@ async function main() {
136
182
  else if (options.command === "share") result = share(options);
137
183
  else if (options.command === "pull") result = pull(options);
138
184
  else if (options.command === "sync") result = sync(options);
185
+ else if (options.command === "update") {
186
+ result = await checkUpdates(options);
187
+ if (result.refreshNeeded) result.backgroundRefreshStarted = launchUpdateRefresh(options);
188
+ }
139
189
  else result = doctor(options);
140
190
  print(result, options.json);
141
191
  if (result.ok === false || result.installed === false || result.clean === false || result.conflicts?.length) process.exitCode = 2;
@@ -150,4 +200,4 @@ async function main() {
150
200
 
151
201
  if (require.main === module) main();
152
202
 
153
- module.exports = { parseArgs, print };
203
+ module.exports = { launchUpdateRefresh, parseArgs, print };
@@ -151,14 +151,57 @@ djournal install --instructions-only
151
151
  ```bash
152
152
  djournal status
153
153
  djournal doctor
154
+ djournal update check
154
155
  ```
155
156
 
156
- `status` reports installed files and cleanliness. `doctor` checks the local
157
- environment and harness configuration. For Pi it reports extension presence
158
- and reminds you that project trust is required; it does not inspect or change
159
- Pi's private trust state.
157
+ `status` reports installed files, cleanliness, the executing CLI version, the
158
+ project asset version, and cached npm release availability. `doctor` checks the
159
+ local environment and harness configuration. For Pi it reports extension
160
+ presence and reminds you that project trust is required; it does not inspect or
161
+ change Pi's private trust state.
162
+
163
+ ## Update notifications
164
+
165
+ djournal checks npm release metadata without delaying session startup. A
166
+ session reads `update-check.json` under `DJOURNAL_HOME` (default:
167
+ `~/.djournal/update-check.json`) and, when that cache is older than 24 hours,
168
+ starts a bounded background refresh for a later session. Registry failures are
169
+ silent in this passive path.
170
+
171
+ When a cached release is newer than the executing CLI, every new session shows
172
+ an update notice until the newer package is installed. When the CLI is newer
173
+ than a project's installed hooks and rules, every new session instead—or
174
+ additionally—reminds you to upgrade those project assets.
175
+
176
+ Check immediately:
177
+
178
+ ```bash
179
+ djournal update check
180
+ djournal update check --json
181
+ ```
182
+
183
+ For a global installation, update both layers:
184
+
185
+ ```bash
186
+ npm install -g djournal@latest
187
+ djournal upgrade
188
+ ```
189
+
190
+ Passive checks are enabled by default. Configure the interval or disable them
191
+ for a project:
192
+
193
+ ```bash
194
+ djournal config updates.intervalHours 24
195
+ djournal config updates.enabled false
196
+ ```
197
+
198
+ Set `NO_UPDATE_NOTIFIER=1` to disable passive checks and notices for the current
199
+ environment. CI and test environments skip them automatically. Explicit
200
+ `djournal update check` commands still perform a foreground check and report
201
+ errors.
160
202
 
161
203
  ## Related docs
162
204
 
163
205
  - [Remote Git sync setup](remote-sync.md)
206
+ - [Read-only team journal access](read-only-team-journal.md)
164
207
  - [Uninstalling and reinstalling](uninstalling.md)
@@ -0,0 +1,150 @@
1
+ # Read-Only Team Journal Access
2
+
3
+ This guide is for people who need to read, recall, and research team journal
4
+ history without publishing their own journal entries back to the shared remote.
5
+ Typical users include PMs, designers, support leads, and executives who want to
6
+ ask an agent about prior decisions without learning the full synchronization
7
+ workflow.
8
+
9
+ ## Current Model
10
+
11
+ djournal does not yet have a single `connect --read-only` command. Today, a
12
+ read-only setup is achieved by combining three controls:
13
+
14
+ - Git credentials that can clone and pull the team journal repository but cannot
15
+ push to it.
16
+ - djournal sync config that enables `pull` but does not enable automatic
17
+ publication.
18
+ - Agent prompts that ask for read-only skills such as `recall`, `research`, and
19
+ `document`, not implementation or journal closure.
20
+
21
+ This still writes local files under the user's djournal home. "Read-only" means
22
+ read-only with respect to the organization remote, not a filesystem mode that
23
+ prevents local cache or canonical-store hydration.
24
+
25
+ ## Setup for a Non-Technical Reader
26
+
27
+ Ask the organization admin for the team journal repository URL and read-only Git
28
+ access. Then use this script-like sequence in a terminal from a working folder:
29
+
30
+ ```bash
31
+ npm install -g djournal
32
+ git clone <team-journal-repository-url> team-journal
33
+ cd team-journal
34
+ djournal install --instructions-only
35
+ djournal config sync.enabled true
36
+ djournal config sync.mode standalone
37
+ djournal config sync.path .
38
+ djournal config sync.auto false
39
+ djournal pull
40
+ djournal status
41
+ ```
42
+
43
+ Use `--instructions-only` when the person only needs portable journal skills and
44
+ does not need editor-specific hooks. Use a harness install instead when they
45
+ will use the journal from Codex, Claude Code, or Pi:
46
+
47
+ ```bash
48
+ djournal install --harness codex
49
+ djournal install --harness claude-code
50
+ djournal install --harness pi
51
+ ```
52
+
53
+ Do not run these commands in a read-only consumer setup:
54
+
55
+ ```bash
56
+ djournal share
57
+ djournal sync
58
+ ```
59
+
60
+ If read-only Git permissions are configured correctly, accidental pushes should
61
+ fail at the remote even if someone runs a publication command.
62
+
63
+ ## Copy/Paste Agent Prompt
64
+
65
+ Use this prompt after installation when asking an LLM agent to connect the local
66
+ checkout to the remote journal in read-only mode:
67
+
68
+ ```text
69
+ Set up djournal for read-only team journal access.
70
+
71
+ The team journal repository is: <paste repository URL>
72
+ I only need to recall and research existing decisions. Do not publish, share,
73
+ sync, push, or create journal entries unless I explicitly ask later.
74
+
75
+ Please:
76
+ 1. Verify Node.js and npm are available.
77
+ 2. Install or update djournal with `npm install -g djournal`.
78
+ 3. Clone the team journal repository if it is not already cloned.
79
+ 4. Run `djournal install --instructions-only` in the cloned journal repository.
80
+ 5. Configure standalone pull access with:
81
+ - `djournal config sync.enabled true`
82
+ - `djournal config sync.mode standalone`
83
+ - `djournal config sync.path .`
84
+ - `djournal config sync.auto false`
85
+ 6. Run `djournal pull` and `djournal status`.
86
+ 7. Report whether recall is ready and show the active work item if one exists.
87
+
88
+ Keep this setup read-only for the organization remote. If a command would write
89
+ to the remote, stop and explain why.
90
+ ```
91
+
92
+ ## Reader Prompts
93
+
94
+ Good prompts for read-only users:
95
+
96
+ ```text
97
+ Recall why we chose the current billing webhook retry strategy.
98
+ ```
99
+
100
+ ```text
101
+ Find product decisions about onboarding and summarize the evidence.
102
+ ```
103
+
104
+ ```text
105
+ Research the journal history for risks in changing the checkout flow. Do not
106
+ edit files or write a journal entry.
107
+ ```
108
+
109
+ ```text
110
+ Show the timeline for the mobile launch work item and list unresolved decisions.
111
+ ```
112
+
113
+ Avoid prompts that imply write behavior unless the user really intends to
114
+ contribute:
115
+
116
+ - "Implement this"
117
+ - "Record a decision"
118
+ - "Share this work"
119
+ - "Sync my journal"
120
+
121
+ ## Organization Admin Checklist
122
+
123
+ For a reader-friendly remote:
124
+
125
+ - Put shared journal projection content in a standalone Git repository.
126
+ - Grant readers clone/pull access only.
127
+ - Keep sensitive or local-only work out of the shared projection.
128
+ - Publish only reviewed work items with `djournal share` and `djournal sync`
129
+ from a maintainer machine or CI account.
130
+ - Provide the repository URL and the copy/paste setup prompt above.
131
+
132
+ ## Product Gaps
133
+
134
+ The current workflow is usable but too manual for non-technical people. A better
135
+ first-class experience would add:
136
+
137
+ - `djournal connect <repo-url> --read-only`, which clones or opens the remote,
138
+ installs instructions, configures standalone pull, disables auto-sync, and
139
+ runs status.
140
+ - `djournal recall-ready`, or an expanded `status`, that explains in plain
141
+ language whether the local reader can use recall.
142
+ - A config flag such as `sync.readOnly: true` that causes `share` and `sync` to
143
+ fail before attempting Git publication.
144
+ - Documentation or generated prompts tailored per harness.
145
+
146
+ ## Related docs
147
+
148
+ - [Installation and repository layouts](installation.md)
149
+ - [Remote Git sync setup](remote-sync.md)
150
+ - [Visibility and sharing](visibility-and-sharing.md)
@@ -181,5 +181,6 @@ The durable team memory is the work item content: `work.md`, `journal/`,
181
181
 
182
182
  ## Related docs
183
183
 
184
+ - [Read-only team journal access](read-only-team-journal.md)
184
185
  - [Visibility and sharing](visibility-and-sharing.md)
185
186
  - [Architecture and data model](architecture.md)
@@ -14,6 +14,13 @@ const {
14
14
  removeManagedBlock,
15
15
  upsertManagedBlock,
16
16
  } = require("./merge.js");
17
+ const {
18
+ cacheIsStale,
19
+ deriveUpdateState,
20
+ passiveChecksEnabled,
21
+ readCache: readUpdateCache,
22
+ refreshCache: refreshUpdateCache,
23
+ } = require("../update-checker.js");
17
24
 
18
25
  const SCHEMA_VERSION = 1;
19
26
  const SUPPORTED_HARNESSES = ["codex", "claude-code", "pi"];
@@ -167,6 +174,10 @@ function defaultProjectConfig(target, store) {
167
174
  default: "local_only",
168
175
  sharedWorkItems: {},
169
176
  },
177
+ updates: {
178
+ enabled: true,
179
+ intervalHours: 24,
180
+ },
170
181
  };
171
182
  }
172
183
 
@@ -255,6 +266,10 @@ function packageVersion(sourceRoot) {
255
266
  return parseJson(fs.readFileSync(path.join(sourceRoot, "package.json")), "package.json").version;
256
267
  }
257
268
 
269
+ function packageSourceRoot(options = {}) {
270
+ return path.resolve(options.sourceRoot || path.join(__dirname, "../.."));
271
+ }
272
+
258
273
  function commandExists(command, env = process.env) {
259
274
  const pathValue = env.PATH || "";
260
275
  const extensions = process.platform === "win32"
@@ -414,7 +429,7 @@ function markdownRecord(target, relative, body, oldRecord, harness) {
414
429
 
415
430
  function journalAccessFragment(harness, store) {
416
431
  if (harness !== "claude-code") return {};
417
- const commands = ["status", "doctor", "config", "share", "sync"];
432
+ const commands = ["status", "doctor", "config", "share", "sync", "update"];
418
433
  return {
419
434
  permissions: {
420
435
  additionalDirectories: [store.root],
@@ -1288,9 +1303,54 @@ function recordStatus(target, record) {
1288
1303
  function status(options) {
1289
1304
  const target = checkTarget(options.target || process.cwd());
1290
1305
  const manifest = loadManifest(target);
1291
- if (!manifest) return { installed: false, target };
1306
+ const config = readProjectConfig(projectContext(target, options));
1307
+ const cache = readUpdateCache(options);
1308
+ const updateState = deriveUpdateState({
1309
+ cliVersion: packageVersion(packageSourceRoot(options)),
1310
+ projectVersion: manifest?.toolVersion,
1311
+ cache,
1312
+ });
1313
+ const updateChecksEnabled = passiveChecksEnabled(config, options.env || process.env, { allowTest: options.allowTest });
1314
+ if (!manifest) return { installed: false, target, ...updateState, updateChecksEnabled };
1292
1315
  const files = manifest.files.map((record) => ({ path: record.path, mode: record.mode, status: recordStatus(target, record) }));
1293
- return { installed: true, target, toolVersion: manifest.toolVersion, harnesses: manifest.harnesses, files, clean: files.every((file) => file.status === "clean") };
1316
+ return {
1317
+ installed: true,
1318
+ target,
1319
+ toolVersion: manifest.toolVersion,
1320
+ ...updateState,
1321
+ updateChecksEnabled,
1322
+ harnesses: manifest.harnesses,
1323
+ files,
1324
+ clean: files.every((file) => file.status === "clean"),
1325
+ };
1326
+ }
1327
+
1328
+ async function checkUpdates(options) {
1329
+ const target = checkTarget(options.target || process.cwd());
1330
+ const manifest = loadManifest(target);
1331
+ const config = readProjectConfig(projectContext(target, options));
1332
+ const cliVersion = packageVersion(packageSourceRoot(options));
1333
+ const enabled = passiveChecksEnabled(config, options.env || process.env, { allowTest: options.allowTest });
1334
+ let cache = readUpdateCache(options);
1335
+ let refreshed = false;
1336
+ if (!options.passive || options.refreshCache) {
1337
+ try {
1338
+ cache = await refreshUpdateCache({ ...options, cliVersion, packageName: "djournal" });
1339
+ refreshed = true;
1340
+ } catch (error) {
1341
+ throw new InstallerError(error.message, error.code || "UPDATE_CHECK_FAILED");
1342
+ }
1343
+ }
1344
+ const stale = cacheIsStale(cache, { config, now: options.now });
1345
+ return {
1346
+ action: "update-check",
1347
+ target,
1348
+ enabled,
1349
+ stale,
1350
+ refreshNeeded: Boolean(options.passive && enabled && stale),
1351
+ refreshed,
1352
+ ...deriveUpdateState({ cliVersion, projectVersion: manifest?.toolVersion, cache }),
1353
+ };
1294
1354
  }
1295
1355
 
1296
1356
  module.exports = {
@@ -1299,6 +1359,7 @@ module.exports = {
1299
1359
  PROJECT_MARKER_PATH,
1300
1360
  SUPPORTED_HARNESSES,
1301
1361
  applyTransaction,
1362
+ checkUpdates,
1302
1363
  configure,
1303
1364
  detectHarnesses,
1304
1365
  doctor,
@@ -0,0 +1,177 @@
1
+ "use strict";
2
+
3
+ const crypto = require("node:crypto");
4
+ const fs = require("node:fs");
5
+ const os = require("node:os");
6
+ const path = require("node:path");
7
+ const semver = require("semver");
8
+
9
+ const CACHE_FILENAME = "update-check.json";
10
+ const DEFAULT_INTERVAL_HOURS = 24;
11
+ const DEFAULT_TIMEOUT_MS = 3000;
12
+ const MAX_RESPONSE_BYTES = 1024 * 1024;
13
+ const REGISTRY_ACCEPT = "application/vnd.npm.install-v1+json";
14
+
15
+ class UpdateCheckError extends Error {
16
+ constructor(message, code = "UPDATE_CHECK_FAILED") {
17
+ super(message);
18
+ this.name = "UpdateCheckError";
19
+ this.code = code;
20
+ }
21
+ }
22
+
23
+ function djournalHome(options = {}) {
24
+ return path.resolve(options.djournalHome || process.env.DJOURNAL_HOME || path.join(os.homedir(), ".djournal"));
25
+ }
26
+
27
+ function cacheFile(options = {}) {
28
+ return path.resolve(options.cacheFile || path.join(djournalHome(options), CACHE_FILENAME));
29
+ }
30
+
31
+ function validVersion(value) {
32
+ return typeof value === "string" ? semver.valid(value) : null;
33
+ }
34
+
35
+ function normalizeCache(value) {
36
+ if (!value || typeof value !== "object" || Array.isArray(value)) return null;
37
+ const latestVersion = validVersion(value.latestVersion);
38
+ const checkedAt = typeof value.checkedAt === "string" && Number.isFinite(Date.parse(value.checkedAt))
39
+ ? new Date(value.checkedAt).toISOString()
40
+ : null;
41
+ const distTag = typeof value.distTag === "string" && value.distTag ? value.distTag : null;
42
+ if (!latestVersion || !checkedAt || !distTag) return null;
43
+ return { checkedAt, latestVersion, distTag };
44
+ }
45
+
46
+ function readCache(options = {}) {
47
+ try {
48
+ const file = cacheFile(options);
49
+ const stat = fs.statSync(file);
50
+ if (!stat.isFile() || stat.size > MAX_RESPONSE_BYTES) return null;
51
+ return normalizeCache(JSON.parse(fs.readFileSync(file, "utf8")));
52
+ } catch {
53
+ return null;
54
+ }
55
+ }
56
+
57
+ function writeCache(value, options = {}) {
58
+ const normalized = normalizeCache(value);
59
+ if (!normalized) throw new UpdateCheckError("update cache is invalid", "INVALID_UPDATE_CACHE");
60
+ const file = cacheFile(options);
61
+ const directory = path.dirname(file);
62
+ fs.mkdirSync(directory, { recursive: true, mode: 0o700 });
63
+ const temporary = path.join(directory, `.${path.basename(file)}.${process.pid}.${crypto.randomBytes(4).toString("hex")}.tmp`);
64
+ try {
65
+ fs.writeFileSync(temporary, `${JSON.stringify(normalized, null, 2)}\n`, { mode: 0o600 });
66
+ fs.renameSync(temporary, file);
67
+ } catch (error) {
68
+ try { fs.unlinkSync(temporary); } catch {}
69
+ throw error;
70
+ }
71
+ return normalized;
72
+ }
73
+
74
+ function intervalHours(config = {}) {
75
+ const value = config?.updates?.intervalHours;
76
+ return Number.isFinite(value) && value > 0 ? value : DEFAULT_INTERVAL_HOURS;
77
+ }
78
+
79
+ function cacheIsStale(cache, options = {}) {
80
+ if (!cache) return true;
81
+ const now = options.now instanceof Date ? options.now.getTime() : Number(options.now ?? Date.now());
82
+ const checkedAt = Date.parse(cache.checkedAt);
83
+ const intervalMs = intervalHours(options.config) * 60 * 60 * 1000;
84
+ return !Number.isFinite(now) || !Number.isFinite(checkedAt) || now - checkedAt >= intervalMs;
85
+ }
86
+
87
+ function environmentFlag(value) {
88
+ return typeof value === "string" ? !["", "0", "false"].includes(value.toLowerCase()) : Boolean(value);
89
+ }
90
+
91
+ function passiveChecksEnabled(config = {}, env = process.env, options = {}) {
92
+ if (config?.updates?.enabled === false) return false;
93
+ if (environmentFlag(env.NO_UPDATE_NOTIFIER) || environmentFlag(env.CI)) return false;
94
+ if (!options.allowTest && (env.NODE_ENV === "test" || environmentFlag(env.NODE_TEST_CONTEXT))) return false;
95
+ return true;
96
+ }
97
+
98
+ function deriveUpdateState(options = {}) {
99
+ const cliVersion = validVersion(options.cliVersion);
100
+ const projectVersion = validVersion(options.projectVersion);
101
+ const cache = normalizeCache(options.cache);
102
+ const latestVersion = cache?.latestVersion || null;
103
+ return {
104
+ cliVersion,
105
+ projectVersion,
106
+ latestVersion,
107
+ checkedAt: cache?.checkedAt || null,
108
+ distTag: cache?.distTag || options.distTag || "latest",
109
+ updateAvailable: Boolean(cliVersion && latestVersion && semver.gt(latestVersion, cliVersion)),
110
+ projectUpdateAvailable: Boolean(cliVersion && projectVersion && semver.gt(cliVersion, projectVersion)),
111
+ };
112
+ }
113
+
114
+ async function fetchLatest(options = {}) {
115
+ const fetchImpl = options.fetchImpl || globalThis.fetch;
116
+ if (typeof fetchImpl !== "function") throw new UpdateCheckError("fetch is unavailable", "UPDATE_FETCH_UNAVAILABLE");
117
+ const packageName = options.packageName || "djournal";
118
+ const distTag = options.distTag || "latest";
119
+ const timeoutMs = options.timeoutMs || DEFAULT_TIMEOUT_MS;
120
+ const signal = options.signal || AbortSignal.timeout(timeoutMs);
121
+ let response;
122
+ try {
123
+ response = await fetchImpl(`https://registry.npmjs.org/${encodeURIComponent(packageName)}`, {
124
+ headers: {
125
+ accept: REGISTRY_ACCEPT,
126
+ "user-agent": `${packageName}/${options.cliVersion || "unknown"}`,
127
+ },
128
+ signal,
129
+ });
130
+ } catch (error) {
131
+ throw new UpdateCheckError(`npm registry request failed: ${error.message}`, "UPDATE_NETWORK_FAILED");
132
+ }
133
+ if (!response || response.ok !== true) {
134
+ throw new UpdateCheckError(`npm registry returned HTTP ${response?.status || "unknown"}`, "UPDATE_HTTP_FAILED");
135
+ }
136
+ const text = await response.text();
137
+ if (Buffer.byteLength(text) > MAX_RESPONSE_BYTES) {
138
+ throw new UpdateCheckError("npm registry response is too large", "UPDATE_RESPONSE_INVALID");
139
+ }
140
+ let metadata;
141
+ try { metadata = JSON.parse(text); } catch {
142
+ throw new UpdateCheckError("npm registry response is not valid JSON", "UPDATE_RESPONSE_INVALID");
143
+ }
144
+ const latestVersion = validVersion(metadata?.["dist-tags"]?.[distTag]);
145
+ if (!latestVersion) {
146
+ throw new UpdateCheckError(`npm registry response has no valid ${distTag} version`, "UPDATE_RESPONSE_INVALID");
147
+ }
148
+ return { latestVersion, distTag };
149
+ }
150
+
151
+ async function refreshCache(options = {}) {
152
+ const latest = await fetchLatest(options);
153
+ const now = options.now instanceof Date ? options.now : new Date(options.now ?? Date.now());
154
+ if (!Number.isFinite(now.getTime())) throw new UpdateCheckError("current time is invalid", "UPDATE_TIME_INVALID");
155
+ return writeCache({ ...latest, checkedAt: now.toISOString() }, options);
156
+ }
157
+
158
+ module.exports = {
159
+ CACHE_FILENAME,
160
+ DEFAULT_INTERVAL_HOURS,
161
+ DEFAULT_TIMEOUT_MS,
162
+ MAX_RESPONSE_BYTES,
163
+ REGISTRY_ACCEPT,
164
+ UpdateCheckError,
165
+ cacheFile,
166
+ cacheIsStale,
167
+ deriveUpdateState,
168
+ djournalHome,
169
+ fetchLatest,
170
+ intervalHours,
171
+ normalizeCache,
172
+ passiveChecksEnabled,
173
+ readCache,
174
+ refreshCache,
175
+ validVersion,
176
+ writeCache,
177
+ };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "djournal",
3
- "version": "0.6.0",
3
+ "version": "0.7.0",
4
4
  "description": "Durable project memory for coding agents, stored as linked Markdown",
5
5
  "type": "commonjs",
6
6
  "bin": {
@@ -26,7 +26,7 @@
26
26
  "check:pr-title": "node scripts/check-pr-title.js",
27
27
  "link:global": "npm link",
28
28
  "release": "semantic-release",
29
- "test": "node tests/journal-hook.test.js && node tests/pi-adapter.test.js && node tests/installer/installer.test.js && node tests/release-policy.test.js && node tests/skill-instructions.test.js && npm run check:package",
29
+ "test": "node tests/update-checker.test.js && node tests/journal-hook.test.js && node tests/pi-adapter.test.js && node tests/installer/installer.test.js && node tests/release-policy.test.js && node tests/skill-instructions.test.js && npm run check:package",
30
30
  "prepublishOnly": "npm test"
31
31
  },
32
32
  "repository": {
@@ -54,5 +54,8 @@
54
54
  },
55
55
  "devDependencies": {
56
56
  "semantic-release": "25.0.3"
57
+ },
58
+ "dependencies": {
59
+ "semver": "7.8.5"
57
60
  }
58
61
  }