1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
use crate::work_event::{ArtifactFile, ConflictPosition, DiffHunk, WorkEventPayload};
use crate::{CliError, CliResult};
use clap::{Args, Subcommand};
use fs2::FileExt;
use std::fs;
use std::io::{Read, Seek, Write};
use std::path::PathBuf;
#[derive(Debug, Args)]
pub struct ReportArgs {
#[command(subcommand)]
pub kind: ReportKind,
}
/// Flags shared by every `zynk report <kind>` subcommand: where the file-first
/// artifact lands (`--root`), how it projects (`--db`/`--no-db`, ADR 028), and
/// who/when authored the event (`--session-id`/`--actor`/`--timestamp`).
#[derive(Debug, Args)]
pub struct Common {
#[arg(long, default_value = "outputs")]
pub root: PathBuf,
#[arg(long)]
pub db: Option<PathBuf>,
#[arg(long)]
pub no_db: bool,
#[arg(long)]
pub session_id: String,
#[arg(long)]
pub actor: String,
#[arg(long)]
pub timestamp: Option<String>,
}
/// The work-event kinds producible in M1 (ADR 033): the five telemetry kinds
/// plus the rich diff/artifact/gate/conflict kinds.
#[derive(Debug, Subcommand)]
pub enum ReportKind {
/// Record a `think` event (free reasoning text).
Think {
#[command(flatten)]
common: Common,
#[arg(long)]
text: String,
},
/// Record a `system` event (operational note; distinct from a status event).
System {
#[command(flatten)]
common: Common,
#[arg(long)]
text: String,
},
/// Record a `tool` invocation event.
Tool {
#[command(flatten)]
common: Common,
#[arg(long)]
name: String,
#[arg(long, default_value = "")]
arg: String,
#[arg(long, default_value = "")]
output: String,
#[arg(long)]
ok: bool,
},
/// Record a `plan` event (a title + one or more `--item` checklist entries).
Plan {
#[command(flatten)]
common: Common,
#[arg(long)]
title: String,
#[arg(long = "item")]
items: Vec<String>,
},
/// Record a `usage` event (per-agent token/cost telemetry).
Usage {
#[command(flatten)]
common: Common,
#[arg(long)]
agent: String,
#[arg(long)]
tokens: u64,
#[arg(long)]
cost_cents: Option<u64>,
},
/// Record a `diff` event: one changed file with summary counts and one or
/// more `--hunk op:text` lines (op ∈ add|rem|meta).
Diff {
#[command(flatten)]
common: Common,
#[arg(long)]
file: String,
#[arg(long, default_value_t = 0)]
added: u32,
#[arg(long, default_value_t = 0)]
removed: u32,
/// Repeated `op:text` (e.g. `add:fn x() {}`); op ∈ add|rem|meta.
#[arg(long = "hunk")]
hunks: Vec<String>,
},
/// Record an `artifact` event: one or more `--file path:add:rem` entries.
/// Dual-projects into the `artifacts` table (one row per path).
Artifact {
#[command(flatten)]
common: Common,
/// Repeated `path:add:rem` (e.g. `src/mid.rs:96:1`).
#[arg(long = "file")]
files: Vec<String>,
},
/// Record a `gate` event: a decision point with a title, summary, proposer,
/// and one or more `--action` options.
Gate {
#[command(flatten)]
common: Common,
#[arg(long)]
title: String,
#[arg(long, default_value = "")]
summary: String,
#[arg(long, default_value = "")]
proposer: String,
/// Repeated action label (e.g. `--action Approve --action "Request changes"`).
#[arg(long = "action")]
actions: Vec<String>,
},
/// Record a `conflict` event: a disputed topic with one or more
/// `--position from:stance:text:tradeoff` entries plus a recommendation.
Conflict {
#[command(flatten)]
common: Common,
#[arg(long)]
topic: String,
/// Repeated `from:stance:text:tradeoff` (the last field may contain `:`).
#[arg(long = "position")]
positions: Vec<String>,
#[arg(long, default_value = "")]
recommended: String,
/// Repeated option label.
#[arg(long = "option")]
options: Vec<String>,
},
}
/// Parse a repeated `--hunk op:text` flag. Splits once on `:` so `text` may
/// itself contain colons (e.g. `meta:@@ -1,3 +1,4 @@`).
fn parse_hunk(raw: &str) -> CliResult<DiffHunk> {
let (op, text) = raw
.split_once(':')
.ok_or_else(|| CliError::usage(format!("--hunk must be `op:text` (got {raw:?})")))?;
if op.trim().is_empty() {
return Err(CliError::usage("--hunk op must be non-empty"));
}
// ADR 033 D3: op ∈ add/rem/meta. The binding enforcement lives in
// WorkEventPayload::validate() (so it can't be bypassed); this surfaces a
// clearer producer-side usage error early.
if !matches!(op, "add" | "rem" | "meta") {
return Err(CliError::usage(format!(
"--hunk op must be one of add/rem/meta (got {op:?})"
)));
}
Ok(DiffHunk {
op: op.to_string(),
text: text.to_string(),
})
}
/// Parse a repeated `--file path:add:rem` flag into a typed `ArtifactFile`.
/// `add`/`rem` are the last two `:`-fields so a path itself never sees a colon
/// in practice; they default to 0 when omitted.
fn parse_artifact_file(raw: &str) -> CliResult<ArtifactFile> {
let fields: Vec<&str> = raw.rsplitn(3, ':').collect();
// rsplitn yields fields in reverse: [rem, add, path] for `path:add:rem`.
let (path, add, rem) = match fields.as_slice() {
[rem, add, path] => (path.to_string(), add.to_string(), rem.to_string()),
[path] => (path.to_string(), "0".to_string(), "0".to_string()),
_ => {
return Err(CliError::usage(format!(
"--file must be `path:add:rem` (got {raw:?})"
)))
}
};
if path.trim().is_empty() {
return Err(CliError::usage("--file path must be non-empty"));
}
let add: u32 = add
.parse()
.map_err(|_| CliError::usage(format!("--file add must be a number (got {add:?})")))?;
let rem: u32 = rem
.parse()
.map_err(|_| CliError::usage(format!("--file rem must be a number (got {rem:?})")))?;
Ok(ArtifactFile { path, add, rem })
}
/// Parse a repeated `--position from:stance:text:tradeoff` flag. Splits into
/// exactly four fields; the trailing `tradeoff` keeps any remaining colons.
fn parse_position(raw: &str) -> CliResult<ConflictPosition> {
let mut parts = raw.splitn(4, ':');
let from = parts.next().unwrap_or_default();
let stance = parts.next();
let text = parts.next();
let tradeoff = parts.next();
match (stance, text, tradeoff) {
(Some(stance), Some(text), Some(tradeoff)) => {
if from.trim().is_empty() {
return Err(CliError::usage("--position from must be non-empty"));
}
Ok(ConflictPosition {
from: from.to_string(),
stance: stance.to_string(),
text: text.to_string(),
tradeoff: tradeoff.to_string(),
})
}
_ => Err(CliError::usage(format!(
"--position must be `from:stance:text:tradeoff` (got {raw:?})"
))),
}
}
impl ReportKind {
fn common(&self) -> &Common {
match self {
ReportKind::Think { common, .. }
| ReportKind::System { common, .. }
| ReportKind::Tool { common, .. }
| ReportKind::Plan { common, .. }
| ReportKind::Usage { common, .. }
| ReportKind::Diff { common, .. }
| ReportKind::Artifact { common, .. }
| ReportKind::Gate { common, .. }
| ReportKind::Conflict { common, .. } => common,
}
}
fn payload(&self) -> CliResult<WorkEventPayload> {
Ok(match self {
ReportKind::Think { text, .. } => WorkEventPayload::Think { text: text.clone() },
ReportKind::System { text, .. } => WorkEventPayload::System { text: text.clone() },
ReportKind::Tool {
name,
arg,
output,
ok,
..
} => WorkEventPayload::Tool {
name: name.clone(),
arg: arg.clone(),
output: output.clone(),
ok: *ok,
},
ReportKind::Plan { title, items, .. } => WorkEventPayload::Plan {
title: title.clone(),
checklist: items.clone(),
},
ReportKind::Usage {
agent,
tokens,
cost_cents,
..
} => WorkEventPayload::Usage {
agent: agent.clone(),
tokens: *tokens,
cost_cents: *cost_cents,
},
ReportKind::Diff {
file,
added,
removed,
hunks,
..
} => WorkEventPayload::Diff {
file: file.clone(),
added: *added,
removed: *removed,
hunks: hunks
.iter()
.map(|h| parse_hunk(h))
.collect::<CliResult<_>>()?,
},
ReportKind::Artifact { files, .. } => WorkEventPayload::Artifact {
files: files
.iter()
.map(|f| parse_artifact_file(f))
.collect::<CliResult<_>>()?,
},
ReportKind::Gate {
title,
summary,
proposer,
actions,
..
} => WorkEventPayload::Gate {
title: title.clone(),
summary: summary.clone(),
proposer: proposer.clone(),
actions: actions.clone(),
},
ReportKind::Conflict {
topic,
positions,
recommended,
options,
..
} => WorkEventPayload::Conflict {
topic: topic.clone(),
positions: positions
.iter()
.map(|p| parse_position(p))
.collect::<CliResult<_>>()?,
recommended: recommended.clone(),
options: options.clone(),
},
})
}
}
pub fn run(args: ReportArgs) -> CliResult<()> {
let kind = args.kind;
let common = kind.common();
let payload = kind.payload()?;
// ADR 029: validate BEFORE any write.
payload.validate()?;
// ADR 027 / ADR 033 D3: a `--timestamp` is real-RFC3339-validated and
// canonicalized to UTC-`Z` seconds BEFORE the file-first write. An invalid
// value is a usage error (reject loud — no file, no DB side effect), NOT a
// soft-degraded infra failure. The resulting canonical value is then used for
// BOTH the work.md block and the DB projection (consistent canonicalization,
// the same discipline `import`/`project_live_audit_record` already apply).
let timestamp = match &common.timestamp {
Some(raw) => crate::timestamp::canonicalize(raw).ok_or_else(|| {
CliError::usage(format!("--timestamp must be RFC3339 UTC (got {raw:?})"))
})?,
None => crate::timestamp::now_utc_seconds(),
};
// File-first: append a human-readable block to <root>/sessions/<id>/work.md.
let dir = common.root.join("sessions").join(&common.session_id);
fs::create_dir_all(&dir)
.map_err(|e| CliError::failure(format!("failed to create {}: {e}", dir.display())))?;
let stored = payload.to_storage()?;
let work_path = dir.join("work.md");
// v1 M1 R2 P4: a file-rendered per-session `seq` ordinal makes the event identity
// robust at seconds precision — two identical same-second events by the same actor
// are legitimately distinct rows, not a collapsed dedup. `seq` = the 0-based index
// of THIS block among the session's existing work-event blocks: read the current
// work.md ("" if absent) and count via the SAME `count_work_blocks` boundary
// authority the importer uses, BEFORE the append. The new block is the `seq`-th
// (0-based), so it round-trips — a later `db import` re-derives the identical `seq`
// from the file. The count uses the robust exact-fence splitter (P5), so an indented
// payload fence never miscounts.
//
// v1 M1 R3 P6: the count+append is ONE critical section guarded by an exclusive
// file lock (mirrors `audit::write_record_to_file`, fs2::FileExt). v1 is a
// multi-agent protocol, so concurrent `zynk report` producers to a shared
// session's work.md are a designed scenario — without the lock two callers can
// read the same block count, compute the SAME `seq`, and write a duplicate-`seq`
// block, which then collapses on `db import` (INSERT OR IGNORE on the seq-folded
// content_hash) → events silently lost. The flock serializes count+append so each
// producer reads the post-predecessor count and gets a distinct, dense `seq`. The
// lock is held ONLY around the file critical section and RELEASED before the DB
// projection (the DB has its own locking; never hold the file lock across DB I/O —
// same discipline as `audit::project_record`'s "run after the file is durable").
let seq = {
// Open read+write (NOT append): we read the current content under the lock,
// which leaves the cursor at EOF, then write the new block there (= append).
let mut handle = fs::OpenOptions::new()
.read(true)
.write(true)
.create(true)
.truncate(false)
.open(&work_path)
.map_err(|e| CliError::failure(format!("failed to open work.md: {e}")))?;
handle.lock_exclusive().map_err(|e| {
CliError::failure(format!("failed to lock {}: {e}", work_path.display()))
})?;
// Critical section: read existing content (cursor 0 → reads whole file, then
// sits at EOF), derive `seq` from the SAME boundary authority the importer
// uses, build the block, and write it at EOF (= append). Capture the result so
// the lock is always released, even on a read/write error.
let locked = (|| -> CliResult<usize> {
// Explicit seek-to-start (mirrors `audit::write_locked_record`): the
// freshly-opened cursor is already at 0, but seeking makes the read
// position explicit instead of relying on that implicit invariant. No
// behavior change — `read_to_string` then leaves the cursor at EOF, so
// the `write_all` below still appends (no second seek needed).
handle
.seek(std::io::SeekFrom::Start(0))
.map_err(|e| CliError::failure(format!("failed to read work.md: {e}")))?;
let mut existing = String::new();
handle
.read_to_string(&mut existing)
.map_err(|e| CliError::failure(format!("failed to read work.md: {e}")))?;
let seq = crate::db::count_work_blocks(&existing);
let block = format!(
"\n```work-event\nkind={}\nactor={}\ntimestamp={}\nseq={}\n{}```\n",
payload.kind(),
common.actor,
timestamp,
seq,
stored
);
handle
.write_all(block.as_bytes())
.map_err(|e| CliError::failure(format!("failed to write work.md: {e}")))?;
handle
.flush()
.map_err(|e| CliError::failure(format!("failed to flush work.md: {e}")))?;
Ok(seq)
})();
// Release the lock BEFORE the DB projection. Propagate an unlock error (like
// audit), then the captured critical-section result.
let unlock_result = handle.unlock();
if let Err(e) = unlock_result {
return Err(CliError::failure(format!(
"failed to unlock {}: {e}",
work_path.display()
)));
}
locked?
};
// Then project (ADR 028): the default cwd `.zynk/zynk.db` auto-creates WITH
// its self-ignoring `.zynk/.gitignore` (the same path status/audit use); a
// default target soft-degrades on projection error (the file is the durable
// record), an explicit `--db` hard-fails, and `--no-db` skips entirely.
if let Some((db_path, explicit)) =
crate::db::resolve_projection_target(common.db.as_deref(), common.no_db)
.into_path_and_mode()
{
let result = crate::db::project_report(
&db_path,
&common.root,
&common.session_id,
&common.actor,
×tamp,
seq,
&payload,
);
if explicit {
result?;
} else if let Err(error) = result {
eprintln!(
"warning: DB projection skipped (work.md written): {}",
error.message
);
}
}
println!(
"{}/sessions/{}/work.md",
common.root.display(),
common.session_id
);
Ok(())
}