djournal 0.5.1 → 0.6.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.
@@ -7,8 +7,8 @@ second workflow engine and do not own durable state.
7
7
 
8
8
  | Event | Adapter behavior |
9
9
  | --- | --- |
10
- | `session_start` | Inject the active work name and tell the agent to follow `AGENTS.md` |
11
- | `prompt_submit` | Remind the agent to classify the request; preserve explicit opt-out |
10
+ | `session_start` | Pull configured standalone journal transport, then inject active work and `AGENTS.md` context |
11
+ | `prompt_submit` | Pull for explicit journal-sync intent, remind the agent to classify the request, and preserve opt-out |
12
12
  | `mutation_observed` | Optional ephemeral reminder only; never write state |
13
13
  | `before_compact` | Optional reminder to preserve material state before context loss |
14
14
  | `stop` | Validate the final journal status marker and request one closure pass |
@@ -40,7 +40,8 @@ native payloads to these names.
40
40
 
41
41
  ## Invariants
42
42
 
43
- - Hooks are read-only.
43
+ - Hooks do not create or edit semantic journal entries. They may delegate
44
+ configured pull/sync transport to the CLI.
44
45
  - `stop_hook_active: true` always permits stopping.
45
46
  - `closed` markers must resolve to an existing Markdown spine entry under the
46
47
  resolved journal root. Agents emit canonical repository-relative
@@ -158,9 +158,9 @@ function validateClosedPath(root, value) {
158
158
  return !!resolveClosedEntry(root, value);
159
159
  }
160
160
 
161
- function syncSharedWork(root, work, runner) {
161
+ function runJournal(root, args, runner) {
162
162
  const run = runner || ((command, args, options) => spawnSync(command, args, options));
163
- const result = run("journal", ["sync", "--auto", "--work", work.slug], {
163
+ const result = run("journal", args, {
164
164
  cwd: root,
165
165
  encoding: "utf8",
166
166
  timeout: 30000,
@@ -173,15 +173,29 @@ function syncSharedWork(root, work, runner) {
173
173
  return { ok: true, message: (result.stdout || "").trim() };
174
174
  }
175
175
 
176
+ function requestsJournalSync(prompt) {
177
+ const match = prompt.match(/\b(?:sync|synchronize|pull)\s+(?:the\s+)?journal\b|\bjournal\s+(?:sync|synchronize|pull)\b/i);
178
+ if (!match) return false;
179
+ const prefix = prompt.slice(Math.max(0, match.index - 32), match.index);
180
+ return !/\b(?:do\s+not|don't|dont|not|without|avoid|skip)\b[^.!?]*$/i.test(prefix);
181
+ }
182
+
176
183
  function handle(payload, options = {}) {
177
184
  const event = payload.hook_event_name;
178
185
  const root = findRoot(payload.cwd);
179
186
  if (!root) return {};
180
187
 
181
188
  if (event === "SessionStart") {
189
+ let pullMessage = "";
190
+ if (shouldAutoSync(root)) {
191
+ const result = runJournal(root, ["pull", "--auto"], options.journalRunner || options.syncRunner);
192
+ pullMessage = result.ok
193
+ ? " Journal pull completed before loading active work."
194
+ : ` Automatic journal pull failed: ${result.message}`;
195
+ }
182
196
  const work = activeWork(root);
183
197
  const suffix = work ? ` Active work: ${work.slug}.` : " No valid active work is selected.";
184
- return context(event, `Follow AGENTS.md and .agents/rules/AUTOMATION.md.${suffix}`);
198
+ return context(event, `Follow AGENTS.md and .agents/rules/AUTOMATION.md.${pullMessage}${suffix}`);
185
199
  }
186
200
 
187
201
  if (event === "UserPromptSubmit") {
@@ -189,6 +203,13 @@ function handle(payload, options = {}) {
189
203
  if (/\bjournal\s*:\s*off\b/i.test(prompt)) {
190
204
  return context(event, "Journal opt-out applies to this request. End with the journal-status: off marker.");
191
205
  }
206
+ if (requestsJournalSync(prompt)) {
207
+ const result = runJournal(root, ["pull"], options.journalRunner || options.syncRunner);
208
+ const pullMessage = result.ok
209
+ ? "The journal was pulled before handling this explicit synchronization request."
210
+ : `The requested journal pull failed and must be resolved before publication: ${result.message}`;
211
+ return context(event, `${pullMessage} Classify this request using the ambient journal workflow and run journal sync if publication was requested.`);
212
+ }
192
213
  return context(event, "Classify this request using the ambient journal workflow. Close meaningful changed state before the final response, without adding ceremony to read-only or trivial work.");
193
214
  }
194
215
 
@@ -217,11 +238,11 @@ function handle(payload, options = {}) {
217
238
  if (status === "closed") {
218
239
  const work = workBySlug(root, closedEntry.workSlug);
219
240
  if ((work?.shared || work?.visibility === "team_shared") && shouldAutoSync(root)) {
220
- const result = syncSharedWork(root, work, options.syncRunner);
241
+ const result = runJournal(root, ["sync", "--auto", "--work", work.slug], options.journalRunner || options.syncRunner);
221
242
  if (!result.ok) {
222
243
  return context(event, `Journal entry is closed and shared work automatic journal sync failed: ${result.message}`);
223
244
  }
224
- return context(event, "Journal entry is closed and shared work was synchronized.");
245
+ return context(event, "Journal entry is closed; remote work was pulled before shared work was synchronized.");
225
246
  }
226
247
  }
227
248
  return {};
@@ -242,4 +263,4 @@ if (require.main === module) {
242
263
  main();
243
264
  }
244
265
 
245
- module.exports = { handle, parseFrontmatter, resolveClosedEntry, shouldAutoSync };
266
+ module.exports = { handle, parseFrontmatter, requestsJournalSync, resolveClosedEntry, shouldAutoSync };
@@ -14,16 +14,19 @@ Create one project-level work item. Work items may span repositories.
14
14
  - `.agents/rules/METADATA.md`
15
15
  - `.agents/rules/SAFETY.md`
16
16
  - `.agents/rules/STATE.md`
17
- 2. Require a non-empty work name or infer one only when the user's requested
17
+ 2. Run `djournal pull` from the project root before inspecting existing work.
18
+ Continue when synchronization is disabled or no projection exists. Stop and
19
+ report any unresolved pull conflict before creating a work item.
20
+ 3. Require a non-empty work name or infer one only when the user's requested
18
21
  project is unambiguous.
19
- 3. Resolve the journal root according to `STATE.md`. List `<journal-root>/work/`
22
+ 4. Resolve the journal root according to `STATE.md`. List `<journal-root>/work/`
20
23
  when it exists. Reject an equivalent existing work item instead of creating a
21
24
  duplicate.
22
- 4. Build the folder slug as `YYYY-MM-DD-NN-kebab-case-name` using the current UTC
25
+ 5. Build the folder slug as `YYYY-MM-DD-NN-kebab-case-name` using the current UTC
23
26
  date and next unused daily sequence.
24
- 5. Resolve `createdBy`, generate a `wi_` UUIDv7, and capture one canonical UTC
27
+ 6. Resolve `createdBy`, generate a `wi_` UUIDv7, and capture one canonical UTC
25
28
  timestamp according to `METADATA.md`.
26
- 6. Create:
29
+ 7. Create:
27
30
 
28
31
  ```text
29
32
  <journal-root>/work/<slug>/
@@ -34,12 +37,12 @@ Create one project-level work item. Work items may span repositories.
34
37
  └── decisions/
35
38
  ```
36
39
 
37
- 7. Write `work.md` with the exact work-item frontmatter contract. Use:
40
+ 8. Write `work.md` with the exact work-item frontmatter contract. Use:
38
41
  - `status: active`
39
42
  - `visibility: local_only`
40
43
  - identical `createdAt` and `updatedAt`
41
44
  - a concise title and description
42
- 8. Add a short body:
45
+ 9. Add a short body:
43
46
 
44
47
  ```markdown
45
48
  # <Title>
@@ -49,9 +52,9 @@ Create one project-level work item. Work items may span repositories.
49
52
  <What outcome this work item exists to achieve.>
50
53
  ```
51
54
 
52
- 9. Create or update `<journal-root>/state.json` to select the new slug. Preserve
55
+ 10. Create or update `<journal-root>/state.json` to select the new slug. Preserve
53
56
  the exact state shape from `STATE.md` and make the update safely.
54
- 10. Re-read `work.md` and state. Verify slug, IDs, directories, timestamps,
57
+ 11. Re-read `work.md` and state. Verify slug, IDs, directories, timestamps,
55
58
  status, visibility, and JSON validity.
56
59
 
57
60
  ## Constraints
@@ -10,19 +10,22 @@ Switch journal context only. Work items are projects and are not Git branches.
10
10
  ## Procedure
11
11
 
12
12
  1. Read `.agents/rules/STATE.md`, `FEAT.md`, `METADATA.md`, and `SAFETY.md`.
13
- 2. Resolve the journal root according to `STATE.md`; read current state when
13
+ 2. Run `djournal pull` from the project root so remote-only and recently updated
14
+ work is present before selection. Continue when synchronization is disabled
15
+ or no projection exists. Stop and report unresolved pull conflicts.
16
+ 3. Resolve the journal root according to `STATE.md`; read current state when
14
17
  valid.
15
- 3. Enumerate `<journal-root>/work/*/work.md` and show slug, title, status, and
18
+ 4. Enumerate `<journal-root>/work/*/work.md` and show slug, title, status, and
16
19
  visibility. Include legacy folders with incomplete metadata.
17
- 4. Match the argument by exact slug first, then unique title/slug substring.
20
+ 5. Match the argument by exact slug first, then unique title/slug substring.
18
21
  If omitted, missing, or ambiguous, request one explicit selection.
19
- 5. If already selected, report that and stop.
20
- 6. Optionally inspect Git status read-only and mention uncommitted changes, but do
22
+ 6. If already selected, report that and stop.
23
+ 7. Optionally inspect Git status read-only and mention uncommitted changes, but do
21
24
  not commit, stash, switch branches, or block the journal switch.
22
- 7. Update `<journal-root>/state.json` atomically to the selected slug using the
25
+ 8. Update `<journal-root>/state.json` atomically to the selected slug using the
23
26
  exact shape in `STATE.md`.
24
- 8. Re-read state and verify the target folder and `work.md` slug.
25
- 9. Present the selected work's latest spine summary and next steps using the
27
+ 9. Re-read state and verify the target folder and `work.md` slug.
28
+ 10. Present the selected work's latest spine summary and next steps using the
26
29
  `resume` retrieval procedure.
27
30
 
28
31
  ## Constraints
@@ -8,7 +8,7 @@
8
8
  "type": "command",
9
9
  "command": "node",
10
10
  "args": ["${CLAUDE_PROJECT_DIR}/.agents/adapters/shared/journal-hook.js", "--harness", "claude-code"],
11
- "timeout": 10,
11
+ "timeout": 45,
12
12
  "statusMessage": "Loading journal workflow"
13
13
  }
14
14
  ]
@@ -21,7 +21,7 @@
21
21
  "type": "command",
22
22
  "command": "node",
23
23
  "args": ["${CLAUDE_PROJECT_DIR}/.agents/adapters/shared/journal-hook.js", "--harness", "claude-code"],
24
- "timeout": 10
24
+ "timeout": 45
25
25
  }
26
26
  ]
27
27
  }
@@ -33,7 +33,7 @@
33
33
  "type": "command",
34
34
  "command": "node",
35
35
  "args": ["${CLAUDE_PROJECT_DIR}/.agents/adapters/shared/journal-hook.js", "--harness", "claude-code"],
36
- "timeout": 10,
36
+ "timeout": 45,
37
37
  "statusMessage": "Checking journal closure"
38
38
  }
39
39
  ]
package/.codex/hooks.json CHANGED
@@ -7,7 +7,7 @@
7
7
  {
8
8
  "type": "command",
9
9
  "command": "sh -c 'd=\"$PWD\"; while [ \"$d\" != / ] && [ ! -f \"$d/.agents/adapters/shared/journal-hook.js\" ]; do d=\"$(dirname \"$d\")\"; done; [ -f \"$d/.agents/adapters/shared/journal-hook.js\" ] || exit 0; exec node \"$d/.agents/adapters/shared/journal-hook.js\" --harness codex'",
10
- "timeout": 10,
10
+ "timeout": 45,
11
11
  "statusMessage": "Loading journal workflow"
12
12
  }
13
13
  ]
@@ -19,7 +19,7 @@
19
19
  {
20
20
  "type": "command",
21
21
  "command": "sh -c 'd=\"$PWD\"; while [ \"$d\" != / ] && [ ! -f \"$d/.agents/adapters/shared/journal-hook.js\" ]; do d=\"$(dirname \"$d\")\"; done; [ -f \"$d/.agents/adapters/shared/journal-hook.js\" ] || exit 0; exec node \"$d/.agents/adapters/shared/journal-hook.js\" --harness codex'",
22
- "timeout": 10
22
+ "timeout": 45
23
23
  }
24
24
  ]
25
25
  }
@@ -30,7 +30,7 @@
30
30
  {
31
31
  "type": "command",
32
32
  "command": "sh -c 'd=\"$PWD\"; while [ \"$d\" != / ] && [ ! -f \"$d/.agents/adapters/shared/journal-hook.js\" ]; do d=\"$(dirname \"$d\")\"; done; [ -f \"$d/.agents/adapters/shared/journal-hook.js\" ] || exit 0; exec node \"$d/.agents/adapters/shared/journal-hook.js\" --harness codex'",
33
- "timeout": 10,
33
+ "timeout": 45,
34
34
  "statusMessage": "Checking journal closure"
35
35
  }
36
36
  ]
package/README.md CHANGED
@@ -217,6 +217,7 @@ djournal doctor
217
217
  djournal config sync.enabled true
218
218
  djournal share --all
219
219
  djournal share
220
+ djournal pull
220
221
  djournal sync
221
222
  djournal upgrade
222
223
  djournal uninstall
@@ -230,10 +231,11 @@ Existing `AGENTS.md` and `CLAUDE.md` files are never replaced. djournal adds an
230
231
  owned block, updates only that block, and removes only that block during
231
232
  uninstall; surrounding project instructions remain untouched.
232
233
 
233
- `share` marks the active work item in the global sharing index. `sync` is
234
- opt-in; in colocated mode it projects shared work into the product repository
235
- for normal commits, and in standalone mode it projects shared work into a
236
- dedicated journal repository.
234
+ `share` marks the active work item in the global sharing index. `pull` hydrates
235
+ the canonical global store from the Git-backed projection with conservative
236
+ three-way reconciliation. `sync` pulls first, then projects and publishes
237
+ shared work. Colocated mode leaves product-repository Git operations to the
238
+ user; standalone mode performs the configured Git pull and push.
237
239
 
238
240
  ## Status
239
241
 
package/bin/journal.js CHANGED
@@ -8,6 +8,7 @@ const {
8
8
  configure,
9
9
  doctor,
10
10
  install,
11
+ pull,
11
12
  share,
12
13
  sync,
13
14
  status,
@@ -26,6 +27,7 @@ function usage() {
26
27
  journal doctor [--target DIR] [--json]
27
28
  journal config [--target DIR] [KEY [VALUE]] [--dry-run] [--json]
28
29
  journal share [--target DIR] [--work SLUG | --all] [--dry-run] [--json]
30
+ journal pull [--target DIR] [--work SLUG] [--dry-run] [--json]
29
31
  journal sync [--target DIR] [--work SLUG] [--dry-run] [--json]
30
32
 
31
33
  Options:
@@ -42,7 +44,7 @@ Options:
42
44
  function parseArgs(argv) {
43
45
  const args = [...argv];
44
46
  const command = args.shift();
45
- if (!command || !["install", "upgrade", "uninstall", "status", "doctor", "config", "share", "sync"].includes(command)) {
47
+ if (!command || !["install", "upgrade", "uninstall", "status", "doctor", "config", "share", "pull", "sync"].includes(command)) {
46
48
  throw new InstallerError(usage(), "USAGE");
47
49
  }
48
50
  const options = { command, harnesses: [] };
@@ -132,6 +134,7 @@ async function main() {
132
134
  else if (options.command === "status") result = status(options);
133
135
  else if (options.command === "config") result = configure(options);
134
136
  else if (options.command === "share") result = share(options);
137
+ else if (options.command === "pull") result = pull(options);
135
138
  else if (options.command === "sync") result = sync(options);
136
139
  else result = doctor(options);
137
140
  print(result, options.json);
@@ -158,9 +158,10 @@ questions.
158
158
  work such as resume, planning, research, decision capture, documentation,
159
159
  audit, reconciliation, and closure.
160
160
 
161
- Hooks remind agents about the workflow and validate final status markers. Hooks
162
- do not create semantic journal entries. When `.djournal.json` exists, hooks read
163
- active work and sync config from the global project store.
161
+ Hooks remind agents about the workflow, delegate configured synchronization
162
+ transport to the CLI, and validate final status markers. Hooks do not create
163
+ semantic journal entries. When `.djournal.json` exists, hooks read active work
164
+ and sync config from the global project store.
164
165
 
165
166
  For Claude Code, install also injects a narrow permission grant into
166
167
  `.claude/settings.json` for the exact global project store path and safe
@@ -174,6 +175,12 @@ into the shared checker. Because Pi has no blocking stop hook,
174
175
  an invalid final marker causes at most one follow-up turn. Pi project trust is
175
176
  managed by Pi, and external sandboxes must expose the global store.
176
177
 
178
+ Configured standalone session-start hooks invoke `djournal pull --auto` before
179
+ loading active work. Explicit journal-sync prompt intent invokes a manual pull.
180
+ Close hooks invoke `djournal sync --auto --work <slug>`, whose transport ordering
181
+ is pull and reconcile, project canonical work, then commit and push. Hooks never
182
+ implement reconciliation or write semantic entries themselves.
183
+
177
184
  ## Related docs
178
185
 
179
186
  - [Djournal in practice](djournal-in-practice.md)
@@ -18,6 +18,11 @@ At session start, the active work item gives the agent a compact context pack:
18
18
  This lets future sessions start from shaped history rather than broad
19
19
  exploration.
20
20
 
21
+ When standalone automatic sync is enabled, session startup first pulls the
22
+ Git-backed journal and reconciles it into canonical storage. Work initialization
23
+ and switching also pull before enumerating available work, so a colleague can
24
+ select work that was created remotely.
25
+
21
26
  ## Plan before risky work
22
27
 
23
28
  Use a plan entry when the work has multiple phases, cross-component effects, or
@@ -135,6 +140,15 @@ Explicit request:
135
140
  Document how journal sync works for future contributors.
136
141
  ```
137
142
 
143
+ To request an immediate team refresh and publication:
144
+
145
+ ```text
146
+ Sync the journal.
147
+ ```
148
+
149
+ The prompt hook pulls first, and the agent then runs the normal journal sync
150
+ workflow when publication is requested.
151
+
138
152
  Inferred request:
139
153
 
140
154
  ```text
@@ -79,11 +79,13 @@ djournal config sync.enabled true
79
79
  djournal config sync.mode colocated
80
80
  djournal config sync.path .
81
81
  djournal share --work 2026-07-03-01-example
82
+ djournal pull --work 2026-07-03-01-example
82
83
  djournal sync --work 2026-07-03-01-example
83
84
  ```
84
85
 
85
- That copies the shared work item into `./.journal/work/...` so normal product
86
- repository commits can carry it.
86
+ Pull hydrates canonical storage from the current product checkout. Sync pulls
87
+ again, then copies the shared work item into `./.journal/work/...` so normal
88
+ product repository commits can carry it.
87
89
 
88
90
  ## Multi-repository setup
89
91
 
@@ -6,10 +6,11 @@ transport they use for code. There are two different modes:
6
6
  - colocated `.journal/` in a product repository
7
7
  - standalone journal repository for multi-repo or team-wide memory
8
8
 
9
- The `djournal sync` command is opt-in and intended for standalone journal
10
- repositories or colocated projections. The canonical journal stays in
11
- `~/.djournal/projects/<project-key>/`; sync copies explicitly shared work into
12
- the configured Git-backed projection.
9
+ The `djournal pull` and `djournal sync` commands are opt-in and intended for
10
+ standalone journal repositories or colocated projections. The canonical journal
11
+ stays in `~/.djournal/projects/<project-key>/`. Pull hydrates that store from
12
+ the projection; sync pulls first and then copies explicitly shared work back
13
+ into the projection for publication.
13
14
 
14
15
  ## Colocated repository
15
16
 
@@ -102,7 +103,19 @@ from the sharing index does not remove it from Git history or teammates' clones.
102
103
 
103
104
  ## Synchronizing shared work
104
105
 
105
- Run sync manually:
106
+ Pull every projected work item into canonical storage:
107
+
108
+ ```bash
109
+ djournal pull
110
+ ```
111
+
112
+ Or pull one work item:
113
+
114
+ ```bash
115
+ djournal pull --work 2026-07-03-01-git-backed-journal-collaboration
116
+ ```
117
+
118
+ Publish shared work:
106
119
 
107
120
  ```bash
108
121
  djournal sync
@@ -116,11 +129,15 @@ djournal sync --work 2026-07-03-01-git-backed-journal-collaboration
116
129
 
117
130
  Current behavior:
118
131
 
119
- - sync is skipped unless global `config.json` opts in
120
- - unshared work is skipped
121
- - colocated mode copies shared work into the configured product repo projection
122
- - standalone mode copies shared work and then uses conservative Git operations
123
- - unresolved journal conflicts stop sync
132
+ - pull and sync are skipped unless global `config.json` opts in
133
+ - standalone pull runs `git pull --ff-only` before canonical hydration
134
+ - colocated pull hydrates from the current checkout but never pulls the product
135
+ repository itself
136
+ - pull uses the prior synchronized projection as a three-way baseline
137
+ - one-sided edits and non-overlapping text changes merge automatically
138
+ - overlapping edits and remote deletions stop without changing canonical files
139
+ - sync pulls first, skips unshared publication, then projects and pushes
140
+ - Git staging and conflict checks are scoped to `.journal/work`
124
141
 
125
142
  Hook-triggered sync uses the same command path with `--auto` only when
126
143
  global config enables standalone automatic sync and the closed work is shared.
@@ -128,6 +145,26 @@ The hook derives the work item from the validated closed marker path, so a
128
145
  response that closes `.journal/work/<slug>/journal/...` synchronizes that
129
146
  `<slug>` even if `state.json` currently selects a different active work item.
130
147
 
148
+ Configured standalone automatic sync also pulls when a new chat/session starts.
149
+ The `init-work` and `switch` workflows pull before enumerating work, and an
150
+ explicit request such as “sync the journal” triggers a pull before the agent
151
+ handles publication. Automatic hook failures are reported as bounded context;
152
+ explicit pull/sync conflicts exit nonzero for manual resolution.
153
+
154
+ ## Conflict behavior
155
+
156
+ Pull compares three versions of every durable work file:
157
+
158
+ - the last successfully observed projection baseline
159
+ - the canonical local file
160
+ - the current projected remote file
161
+
162
+ If only one side changed, that side is preserved. Non-overlapping concurrent
163
+ text edits are merged. If the same lines changed incompatibly, or the remote
164
+ deleted durable history, pull returns the conflicting logical paths and does not
165
+ apply any canonical changes or advance the baseline. Resolve those files in the
166
+ projection or canonical store, then rerun `djournal pull`.
167
+
131
168
  ## Keep local state local
132
169
 
133
170
  Do not use Git as a blind mirror of every operational file. Treat these as
@@ -135,6 +172,7 @@ local operational state unless a future workflow explicitly says otherwise:
135
172
 
136
173
  - `.journal/state.json`
137
174
  - `.journal/.install/`
175
+ - the canonical store's `.sync/` reconciliation baseline
138
176
  - `.djournal.json` when the team does not want to share the local store pointer
139
177
  - local harness cache or runtime files
140
178
 
@@ -51,7 +51,13 @@ or push for the configured mode.
51
51
 
52
52
  ## Sync and visibility
53
53
 
54
- Run sync:
54
+ Hydrate canonical storage from the shared projection:
55
+
56
+ ```bash
57
+ djournal pull
58
+ ```
59
+
60
+ Then publish shared local work:
55
61
 
56
62
  ```bash
57
63
  djournal sync
@@ -75,9 +81,11 @@ djournal config sync.mode colocated
75
81
  djournal sync
76
82
  ```
77
83
 
78
- In colocated mode, sync copies shared work into the product repository
79
- projection. In standalone mode, sync copies shared work into the standalone
80
- journal repository and performs conservative Git operations.
84
+ In colocated mode, pull reads the current product repository projection without
85
+ performing product Git operations. In standalone mode, pull fast-forwards the
86
+ journal repository before hydrating canonical storage. Sync always pulls first;
87
+ it then copies shared work into the projection and, in standalone mode, commits
88
+ and pushes it.
81
89
 
82
90
  ## Safety model
83
91
 
@@ -753,6 +753,278 @@ function projectJournalRoot(projectionRoot) {
753
753
  return path.join(projectionRoot, ".journal");
754
754
  }
755
755
 
756
+ function syncBaselineWorkRoot(context, slug) {
757
+ return path.join(context.root, ".sync", "base", "work", slug);
758
+ }
759
+
760
+ function readBuffer(file) {
761
+ return readOptional(file);
762
+ }
763
+
764
+ function buffersEqual(left, right) {
765
+ if (left === null || right === null) return left === right;
766
+ return left.equals(right);
767
+ }
768
+
769
+ function durableWorkSlugs(journalRoot) {
770
+ const workRoot = path.join(journalRoot, "work");
771
+ if (!fs.existsSync(workRoot)) return [];
772
+ return fs.readdirSync(workRoot, { withFileTypes: true })
773
+ .filter((entry) => entry.isDirectory() && !entry.isSymbolicLink())
774
+ .map((entry) => entry.name)
775
+ .filter((slug) => !slug.includes("/") && !slug.includes("\\") &&
776
+ fs.existsSync(path.join(workRoot, slug, "work.md")))
777
+ .sort();
778
+ }
779
+
780
+ function mergeJournalText(local, base, remote, options = {}) {
781
+ if ([local, base, remote].some((value) => value.includes(0))) {
782
+ return { ok: false, message: "binary content cannot be merged automatically" };
783
+ }
784
+ const lines = (value) => value.toString("utf8").match(/[^\n]*\n|[^\n]+$/g) || [];
785
+ const localLines = lines(local);
786
+ const baseLines = lines(base);
787
+ const remoteLines = lines(remote);
788
+ if (localLines.length === baseLines.length && remoteLines.length === baseLines.length) {
789
+ const merged = [];
790
+ for (let index = 0; index < baseLines.length; index += 1) {
791
+ if (localLines[index] === remoteLines[index]) merged.push(localLines[index]);
792
+ else if (localLines[index] === baseLines[index]) merged.push(remoteLines[index]);
793
+ else if (remoteLines[index] === baseLines[index]) merged.push(localLines[index]);
794
+ else return { ok: false, message: "overlapping edits" };
795
+ }
796
+ return { ok: true, content: Buffer.from(merged.join("")) };
797
+ }
798
+ const temporary = fs.mkdtempSync(path.join(os.tmpdir(), "djournal-merge-"));
799
+ const localFile = path.join(temporary, "local");
800
+ const baseFile = path.join(temporary, "base");
801
+ const remoteFile = path.join(temporary, "remote");
802
+ try {
803
+ fs.writeFileSync(localFile, local);
804
+ fs.writeFileSync(baseFile, base);
805
+ fs.writeFileSync(remoteFile, remote);
806
+ const result = (options.mergeRunner || spawnSync)("git", ["merge-file", "-p", "--", localFile, baseFile, remoteFile], {
807
+ encoding: null,
808
+ timeout: options.timeout || 30000,
809
+ });
810
+ if (result.error) return { ok: false, message: result.error.message };
811
+ if (result.status !== 0) {
812
+ return { ok: false, message: result.status === 1 ? "overlapping edits" : "git merge-file failed" };
813
+ }
814
+ return { ok: true, content: Buffer.from(result.stdout || "") };
815
+ } finally {
816
+ fs.rmSync(temporary, { recursive: true, force: true });
817
+ }
818
+ }
819
+
820
+ function reconcileWork(context, projectionJournal, slug, options = {}) {
821
+ const canonicalRoot = path.join(context.journalRoot, "work", slug);
822
+ const remoteRoot = path.join(projectionJournal, "work", slug);
823
+ const baselineRoot = syncBaselineWorkRoot(context, slug);
824
+ const comparisonBaseRoot = fs.existsSync(baselineRoot)
825
+ ? baselineRoot
826
+ : path.join(options.fallbackBaselineJournal || projectionJournal, "work", slug);
827
+ const relativeFiles = [...new Set([
828
+ ...listFiles(canonicalRoot),
829
+ ...listFiles(remoteRoot),
830
+ ...listFiles(comparisonBaseRoot),
831
+ ])].sort();
832
+ const changes = [];
833
+ const files = [];
834
+ const conflicts = [];
835
+
836
+ for (const relative of relativeFiles) {
837
+ const canonicalFile = path.join(canonicalRoot, relative);
838
+ const remoteFile = path.join(remoteRoot, relative);
839
+ const baselineFile = path.join(comparisonBaseRoot, relative);
840
+ const local = readBuffer(canonicalFile);
841
+ const remote = readBuffer(remoteFile);
842
+ const base = readBuffer(baselineFile);
843
+ const logicalPath = `.journal/work/${slug}/${relative}`;
844
+
845
+ if (buffersEqual(local, remote)) {
846
+ files.push({ path: logicalPath, status: "unchanged" });
847
+ continue;
848
+ }
849
+ if (base !== null && remote === null) {
850
+ if (local === null) {
851
+ files.push({ path: logicalPath, status: "unchanged" });
852
+ } else {
853
+ conflicts.push(`${logicalPath}: remote deletion requires manual review`);
854
+ }
855
+ continue;
856
+ }
857
+ if (local === null && remote !== null) {
858
+ changes.push({ file: canonicalFile, content: remote });
859
+ files.push({ path: logicalPath, status: "imported" });
860
+ continue;
861
+ }
862
+ if (remote === null) {
863
+ files.push({ path: logicalPath, status: "local" });
864
+ continue;
865
+ }
866
+ if (base !== null && buffersEqual(local, base)) {
867
+ changes.push({ file: canonicalFile, content: remote });
868
+ files.push({ path: logicalPath, status: "imported" });
869
+ continue;
870
+ }
871
+ if (base !== null && buffersEqual(remote, base)) {
872
+ files.push({ path: logicalPath, status: "local" });
873
+ continue;
874
+ }
875
+ if (base === null) {
876
+ conflicts.push(`${logicalPath}: divergent content has no synchronization baseline`);
877
+ continue;
878
+ }
879
+
880
+ const merged = mergeJournalText(local, base, remote, options);
881
+ if (!merged.ok) {
882
+ conflicts.push(`${logicalPath}: ${merged.message}`);
883
+ continue;
884
+ }
885
+ changes.push({ file: canonicalFile, content: merged.content });
886
+ files.push({ path: logicalPath, status: "merged" });
887
+ }
888
+
889
+ return { slug, canonicalRoot, remoteRoot, baselineRoot, changes, files, conflicts };
890
+ }
891
+
892
+ function applyCanonicalChanges(reconciliations) {
893
+ const written = [];
894
+ try {
895
+ for (const reconciliation of reconciliations) {
896
+ for (const change of reconciliation.changes) {
897
+ const previous = readOptional(change.file);
898
+ fs.mkdirSync(path.dirname(change.file), { recursive: true });
899
+ atomicWrite(change.file, change.content);
900
+ written.push({ file: change.file, previous });
901
+ }
902
+ }
903
+ } catch (error) {
904
+ for (const item of written.reverse()) {
905
+ if (item.previous === null) fs.rmSync(item.file, { force: true });
906
+ else atomicWrite(item.file, item.previous);
907
+ }
908
+ throw error;
909
+ }
910
+ }
911
+
912
+ function replaceBaseline(source, destination) {
913
+ const parent = path.dirname(destination);
914
+ fs.mkdirSync(parent, { recursive: true });
915
+ const staged = fs.mkdtempSync(path.join(parent, ".baseline-"));
916
+ const backup = `${destination}.previous-${process.pid}-${Date.now()}`;
917
+ try {
918
+ copyDirectoryContents(source, staged);
919
+ if (fs.existsSync(destination)) fs.renameSync(destination, backup);
920
+ fs.renameSync(staged, destination);
921
+ if (fs.existsSync(backup)) fs.rmSync(backup, { recursive: true, force: true });
922
+ } catch (error) {
923
+ if (fs.existsSync(staged)) fs.rmSync(staged, { recursive: true, force: true });
924
+ if (fs.existsSync(backup) && !fs.existsSync(destination)) fs.renameSync(backup, destination);
925
+ throw error;
926
+ }
927
+ }
928
+
929
+ function pullWithContext(context, config, options = {}) {
930
+ const syncOptions = config.sync && typeof config.sync === "object" ? config.sync : {};
931
+ const target = context.target;
932
+ if (syncOptions.enabled !== true) {
933
+ return { action: "pull", target, skipped: true, reason: "sync is not enabled" };
934
+ }
935
+ if (!["colocated", "standalone"].includes(syncOptions.mode)) {
936
+ return { action: "pull", target, skipped: true, reason: "sync mode is not supported" };
937
+ }
938
+
939
+ const projectionRoot = projectionRootFor(target, config);
940
+ const projectionJournal = projectJournalRoot(projectionRoot);
941
+ if (!fs.existsSync(projectionJournal)) {
942
+ return { action: "pull", target, skipped: true, reason: "journal projection does not exist" };
943
+ }
944
+
945
+ let pulled = false;
946
+ let gitRoot;
947
+ let fallbackBaselineJournal = projectionJournal;
948
+ let projectionSnapshot;
949
+ if (syncOptions.mode === "standalone") {
950
+ gitRoot = gitRootFor(projectionJournal, options);
951
+ const pathspec = journalPathspec(gitRoot, path.join(projectionJournal, "work"));
952
+ const unmerged = runGit(gitRoot, ["diff", "--name-only", "--diff-filter=U", "--", pathspec], options);
953
+ if (unmerged) throw new InstallerError(`unresolved journal conflicts:\n${unmerged}`, "SYNC_CONFLICT");
954
+ const dirty = runGit(gitRoot, ["status", "--porcelain", "--untracked-files=all", "--", pathspec], options);
955
+ if (dirty) throw new InstallerError(`journal projection has uncommitted changes:\n${dirty}`, "SYNC_CONFLICT");
956
+ if (!options.dryRun) {
957
+ projectionSnapshot = fs.mkdtempSync(path.join(os.tmpdir(), "djournal-pull-base-"));
958
+ copyDirectoryContents(projectionJournal, projectionSnapshot);
959
+ fallbackBaselineJournal = projectionSnapshot;
960
+ try {
961
+ runGit(gitRoot, ["pull", "--ff-only"], options);
962
+ pulled = true;
963
+ } catch (error) {
964
+ fs.rmSync(projectionSnapshot, { recursive: true, force: true });
965
+ throw error;
966
+ }
967
+ }
968
+ }
969
+
970
+ try {
971
+ const available = durableWorkSlugs(projectionJournal);
972
+ const slugs = options.work ? available.filter((slug) => slug === options.work) : available;
973
+ if (!slugs.length) {
974
+ return {
975
+ action: "pull",
976
+ target,
977
+ mode: syncOptions.mode,
978
+ work: options.work,
979
+ skipped: true,
980
+ reason: options.work ? "work item is not present in the journal projection" : "no projected work items found",
981
+ pulled,
982
+ };
983
+ }
984
+
985
+ const reconcileOptions = { ...options, fallbackBaselineJournal };
986
+ const reconciliations = slugs.map((slug) => reconcileWork(context, projectionJournal, slug, reconcileOptions));
987
+ const conflicts = reconciliations.flatMap((item) => item.conflicts);
988
+ const files = reconciliations.flatMap((item) => item.files);
989
+ if (conflicts.length || options.dryRun) {
990
+ return {
991
+ action: "pull",
992
+ target,
993
+ mode: syncOptions.mode,
994
+ workItems: slugs,
995
+ files,
996
+ conflicts,
997
+ pulled,
998
+ dryRun: !!options.dryRun,
999
+ };
1000
+ }
1001
+
1002
+ applyCanonicalChanges(reconciliations);
1003
+ for (const reconciliation of reconciliations) {
1004
+ replaceBaseline(reconciliation.remoteRoot, reconciliation.baselineRoot);
1005
+ }
1006
+ return {
1007
+ action: "pull",
1008
+ target,
1009
+ mode: syncOptions.mode,
1010
+ workItems: slugs,
1011
+ files,
1012
+ conflicts: [],
1013
+ pulled,
1014
+ dryRun: false,
1015
+ };
1016
+ } finally {
1017
+ if (projectionSnapshot) fs.rmSync(projectionSnapshot, { recursive: true, force: true });
1018
+ }
1019
+ }
1020
+
1021
+ function pull(options) {
1022
+ const target = checkTarget(options.target || process.cwd());
1023
+ const context = projectContext(target, options);
1024
+ const config = readProjectConfig(context);
1025
+ return pullWithContext(context, config, options);
1026
+ }
1027
+
756
1028
  function projectSharedWork(context, config, work, options = {}) {
757
1029
  const targetRoot = projectionRootFor(context.target, config);
758
1030
  const destinationJournal = projectJournalRoot(targetRoot);
@@ -799,23 +1071,28 @@ function sync(options) {
799
1071
  if (!["colocated", "standalone"].includes(syncOptions.mode)) {
800
1072
  return { action: "sync", target, skipped: true, reason: "sync mode is not standalone" };
801
1073
  }
1074
+ const pulled = pullWithContext(context, config, options);
1075
+ if (pulled.conflicts?.length) {
1076
+ throw new InstallerError(`unresolved journal conflicts:\n${pulled.conflicts.join("\n")}`, "SYNC_CONFLICT");
1077
+ }
802
1078
  const work = readActiveWork(context, options.work);
803
1079
  if (!isWorkShared(config, work.slug)) {
804
1080
  return { action: "sync", target, work: work.slug, skipped: true, reason: "work is not shared" };
805
1081
  }
806
1082
  const projection = projectSharedWork(context, config, work, options);
807
1083
  if (syncOptions.mode === "colocated") {
808
- return { action: "sync", target, work: work.slug, projectionRoot: projection.projectionRoot, files: projection.files, dryRun: !!options.dryRun };
1084
+ if (!options.dryRun) replaceBaseline(
1085
+ path.join(projection.journalRoot, "work", work.slug),
1086
+ syncBaselineWorkRoot(context, work.slug),
1087
+ );
1088
+ return { action: "sync", target, work: work.slug, projectionRoot: projection.projectionRoot, files: projection.files, pulled, dryRun: !!options.dryRun };
809
1089
  }
810
1090
  const gitRoot = gitRootFor(projection.journalRoot, options);
811
- const pathspec = journalPathspec(gitRoot, projection.journalRoot);
1091
+ const pathspec = journalPathspec(gitRoot, path.join(projection.journalRoot, "work"));
812
1092
  const unmerged = runGit(gitRoot, ["diff", "--name-only", "--diff-filter=U", "--", pathspec], options);
813
1093
  if (unmerged) throw new InstallerError(`unresolved journal conflicts:\n${unmerged}`, "SYNC_CONFLICT");
814
- if (options.dryRun) return { action: "sync", target, work: work.slug, projectionRoot: projection.projectionRoot, gitRoot, pathspec, files: projection.files, dryRun: true };
1094
+ if (options.dryRun) return { action: "sync", target, work: work.slug, projectionRoot: projection.projectionRoot, gitRoot, pathspec, files: projection.files, pulled, dryRun: true };
815
1095
 
816
- runGit(gitRoot, ["pull", "--ff-only"], options);
817
- const afterPullUnmerged = runGit(gitRoot, ["diff", "--name-only", "--diff-filter=U", "--", pathspec], options);
818
- if (afterPullUnmerged) throw new InstallerError(`unresolved journal conflicts:\n${afterPullUnmerged}`, "SYNC_CONFLICT");
819
1096
  runGit(gitRoot, ["add", "--", pathspec], options);
820
1097
  let committed = true;
821
1098
  try {
@@ -826,7 +1103,11 @@ function sync(options) {
826
1103
  runGit(gitRoot, ["commit", "-m", `chore(journal): sync ${work.slug}`], options);
827
1104
  }
828
1105
  runGit(gitRoot, ["push"], options);
829
- return { action: "sync", target, work: work.slug, projectionRoot: projection.projectionRoot, gitRoot, pathspec, files: projection.files, committed, pushed: true, auto: !!options.auto };
1106
+ replaceBaseline(
1107
+ path.join(projection.journalRoot, "work", work.slug),
1108
+ syncBaselineWorkRoot(context, work.slug),
1109
+ );
1110
+ return { action: "sync", target, work: work.slug, projectionRoot: projection.projectionRoot, gitRoot, pathspec, files: projection.files, pulled, committed, pushed: true, auto: !!options.auto };
830
1111
  }
831
1112
 
832
1113
  function doctor(options) {
@@ -1024,6 +1305,7 @@ module.exports = {
1024
1305
  djournalHome,
1025
1306
  install,
1026
1307
  loadManifest,
1308
+ pull,
1027
1309
  projectContext,
1028
1310
  recoverTransaction,
1029
1311
  selectHarnesses,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "djournal",
3
- "version": "0.5.1",
3
+ "version": "0.6.0",
4
4
  "description": "Durable project memory for coding agents, stored as linked Markdown",
5
5
  "type": "commonjs",
6
6
  "bin": {