zynk 1.1.0

Portable protocol and helper CLI for multi-agent collaboration.
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
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
use crate::audit::AuditArgs;
use crate::decision::Decision;
use crate::{CliError, CliResult};
use clap::{Args, Subcommand};
use std::path::PathBuf;

#[derive(Debug, Args)]
pub struct DecideArgs {
    #[command(subcommand)]
    pub kind: DecideKind,
}

/// Flags shared by every `zynk decide <type>` subcommand, mirroring
/// `report::Common`: where the file-first audit artifact lands (`--root`), how it
/// projects (`--db`/`--no-db`, ADR 028), and which session/when it was authored
/// (`--session-id`/`--timestamp`). A decision is operator-authored by definition
/// (ADR 033 D4), so the proof hardcodes `source_agent=operator`; there is no
/// `--actor` flag (it would be inert).
#[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 timestamp: Option<String>,
    /// Optional notification (ADR 033 D4 / C4=b): AFTER the decision is durable,
    /// perform a SEPARATE audited `send herdr` (ADR 029) of the decision to the
    /// target herdr pane. Requires `--notify-to` too. On notify FAILURE the
    /// decision STAYS durable and only `operator_decisions` records the failure
    /// (notification_status=failed + error); NO failed/sent audit is written.
    /// The notify outcome is recorded on the PROJECTED decision row, so it is
    /// incompatible with `--no-db` (rejected up front) and, if the default DB
    /// projection soft-degrades (no projected row), the command fails LOUD rather
    /// than dropping the requested send silently.
    #[arg(long, requires = "notify_to")]
    pub notify_pane: Option<String>,
    /// The notification recipient as `agent:address` (ADR 029 `--to`); its address
    /// must equal `--notify-pane`. Requires `--notify-pane` too.
    #[arg(long, requires = "notify_pane")]
    pub notify_to: Option<String>,
    /// herdr executable for the optional notification send (default "herdr");
    /// pointing it at a nonzero-exit binary exercises the transport-failure path.
    #[arg(long, default_value = "herdr")]
    pub herdr_bin: String,
    /// ADR 034 D7 + Codex C5: ALSO retain the FULL decision payload as ciphertext in
    /// the DB custody_vault (in addition to the redacted corpus). The vault lives in
    /// the DB, so this is incompatible with `--no-db` (rejected up front). On
    /// retention failure the command is LOUD nonzero ("record written but custody NOT
    /// retained") AND — per C5 — the optional notify hop is SKIPPED: the requested
    /// custody failed, so we do not proceed to notify a peer.
    #[arg(long)]
    pub retain_custody: bool,
    /// Operator key file for `--retain-custody` (default: derived next to the DB).
    #[arg(long)]
    pub custody_key_file: Option<PathBuf>,
}

/// The operator-decision kinds (ADR 033 D4): one subcommand per `Decision`
/// variant. Gate/Conflict bind a `--ref` work-event id; mode/interrupt/redirect
/// stand alone.
#[derive(Debug, Subcommand)]
pub enum DecideKind {
    /// Record a `gate-decision`: approve or request changes on a `gate` work-event.
    Gate {
        #[command(flatten)]
        common: Common,
        /// The id of the `gate` work-event this decision resolves.
        #[arg(long)]
        r#ref: i64,
        #[arg(long)]
        verdict: String,
        #[arg(long)]
        note: Option<String>,
    },
    /// Record a `conflict-resolve`: pick a resolution for a `conflict` work-event.
    Conflict {
        #[command(flatten)]
        common: Common,
        /// The id of the `conflict` work-event this decision resolves.
        #[arg(long)]
        r#ref: i64,
        #[arg(long)]
        resolution: String,
        #[arg(long)]
        note: Option<String>,
    },
    /// Record a `mode-switch`: change the session's operating mode.
    Mode {
        #[command(flatten)]
        common: Common,
        #[arg(long = "to")]
        to: String,
    },
    /// Record an `interrupt`: pause the active work.
    Interrupt {
        #[command(flatten)]
        common: Common,
        #[arg(long)]
        reason: Option<String>,
    },
    /// Record a `redirect`: hand the work to another agent.
    Redirect {
        #[command(flatten)]
        common: Common,
        #[arg(long = "to")]
        to: String,
        #[arg(long)]
        reason: Option<String>,
    },
}

impl DecideKind {
    fn common(&self) -> &Common {
        match self {
            DecideKind::Gate { common, .. }
            | DecideKind::Conflict { common, .. }
            | DecideKind::Mode { common, .. }
            | DecideKind::Interrupt { common, .. }
            | DecideKind::Redirect { common, .. } => common,
        }
    }

    /// Build the typed `Decision` from the subcommand flags. For gate/conflict the
    /// `--ref` i64 becomes the `target_work_event_id`.
    fn decision(&self) -> CliResult<Decision> {
        Ok(match self {
            DecideKind::Gate {
                r#ref,
                verdict,
                note,
                ..
            } => Decision::Gate {
                target_work_event_id: *r#ref,
                verdict: verdict.clone(),
                note: note.clone(),
            },
            DecideKind::Conflict {
                r#ref,
                resolution,
                note,
                ..
            } => Decision::Conflict {
                target_work_event_id: *r#ref,
                resolution: resolution.clone(),
                note: note.clone(),
            },
            DecideKind::Mode { to, .. } => Decision::Mode {
                mode_to: to.clone(),
            },
            DecideKind::Interrupt { reason, .. } => Decision::Interrupt {
                reason: reason.clone(),
            },
            DecideKind::Redirect { to, reason, .. } => Decision::Redirect {
                target_agent: to.clone(),
                reason: reason.clone(),
            },
        })
    }

    /// The work-event `kind` a bound `--ref` must point at: `gate` for a gate
    /// decision, `conflict` for a conflict resolution. None for the unbound kinds
    /// (mode/interrupt/redirect have no `target_work_event_id`).
    fn expected_ref_kind(&self) -> Option<&'static str> {
        match self {
            DecideKind::Gate { .. } => Some("gate"),
            DecideKind::Conflict { .. } => Some("conflict"),
            _ => None,
        }
    }
}

pub fn run(args: DecideArgs) -> CliResult<()> {
    let kind = args.kind;
    let common = kind.common();
    let decision = kind.decision()?;
    // ADR 029 discipline: validate the typed decision BEFORE any write (never
    // store-bad). A bad verdict/mode/empty field rejects here — no file, no DB.
    decision.validate()?;

    // A notify records its outcome on the PROJECTED `operator_decisions` row, so it
    // is impossible to honor under `--no-db` (file-only — no projected row ever
    // exists). Reject the combination BEFORE any write (validate-before-write) rather
    // than silently dropping the requested notify. `requires` already pairs
    // --notify-pane/--notify-to at the clap layer; either being present means notify
    // was requested.
    if (common.notify_pane.is_some() || common.notify_to.is_some()) && common.no_db {
        return Err(CliError::usage(
            "--notify-pane/--notify-to cannot be combined with --no-db: \
             notification status is recorded on the projected decision",
        ));
    }

    // ADR 034 D7 + Codex C5(2): the custody vault lives in the DB, so `--no-db`
    // (file-only) is incoherent with `--retain-custody`. Reject BEFORE any write —
    // a requested retention that can't be honored must fail loud, never silently
    // no-retain (mirrors the `audit`/`send` retain guard).
    if common.retain_custody && common.no_db {
        return Err(CliError::usage(
            "--retain-custody cannot be combined with --no-db: custody is retained in the DB vault",
        ));
    }

    // Resolve the projection target once (ADR 028): `--no-db` => None; `--db <p>`
    // => Explicit (hard-fail on projection error); default => the auto-created cwd
    // `.zynk/zynk.db` (soft-degrade). Used BOTH for the pre-write ref-kind check
    // and the post-write projection.
    let target = crate::db::resolve_projection_target(common.db.as_deref(), common.no_db);

    // Ref-kind check BEFORE the file write (ADR 027 validate-before-write): a
    // gate/conflict decision binds a `--ref` work-event; if a DB is resolvable,
    // confirm the referenced id exists in the session AND is the expected kind. A
    // wrong-kind or missing ref is a usage error — reject loud, write nothing.
    if let (Some(wid), Some(expected_kind), Some((db_path, _explicit))) = (
        decision.target_work_event_id(),
        kind.expected_ref_kind(),
        target.path_and_mode(),
    ) {
        match crate::db::work_event_kind(db_path, &common.session_id, wid)? {
            Some(actual) if actual == expected_kind => {}
            Some(actual) => {
                return Err(CliError::usage(format!(
                    "--ref {wid} is a {actual} work-event, not a {expected_kind}"
                )))
            }
            None => {
                return Err(CliError::usage(format!(
                    "--ref {wid} not found in session {}",
                    common.session_id
                )))
            }
        }
    }

    // Build the decision audit (ADR 033 D4 conventions): an operator-observed,
    // operator-verified, transport=none proof carrying the serialized decision as
    // its full-redaction payload, with `type`=record_type and `ref`=the bound
    // work-event id. delivery_status=observed (never `sent` — a decision is not a
    // transported message), so the ADR 024 sent+agent boundary never applies.
    let audit_args = AuditArgs {
        profile: None,
        root: common.root.clone(),
        session_id: common.session_id.clone(),
        audit_id: None,
        previous_audit_id: None,
        timestamp: common.timestamp.clone(),
        due: None,
        source_agent: "operator".to_string(),
        source_address: "cli".to_string(),
        target_agent: "none".to_string(),
        target_address: "none".to_string(),
        transport: "none".to_string(),
        workspace_id: "none".to_string(),
        transport_thread_id: None,
        mid: crate::dashboard_write::mint_mid(),
        record_type: decision.record_type().to_string(),
        mode: None,
        r#ref: decision.target_work_event_id().map(|w| w.to_string()),
        re: None,
        command_origin: "operator".to_string(),
        payload: Some(decision.to_storage()?),
        payload_file: None,
        payload_redaction_policy: "full".to_string(),
        payload_ref: None,
        sensitive_category: None,
        excerpt_chars: 12,
        delivery_status: "observed".to_string(),
        observed_by: "operator".to_string(),
        verified_by: "operator".to_string(),
        db: common.db.clone(),
        no_db: common.no_db,
        // ADR 034 D7: `zynk decide` does not expose `--retain-custody` (M3a wires
        // custody only on the `zynk audit` path); the redacted corpus is unchanged.
        retain_custody: false,
        custody_key_file: None,
    };

    // Reuse the audit machinery: validate the rendered args (boundary + enums +
    // RFC3339 timestamp) BEFORE the file write, then write the file (file-first,
    // under the audit.md exclusive lock).
    let profile = crate::profile::load_profile(None)?;
    crate::audit::validate_audit_args(&audit_args, &profile)?;
    let (audit_path, record) = crate::audit::write_audit_file(&audit_args, &profile)?;

    // Project the decision (the immutable audit proof row + the typed
    // operator_decisions row, atomically). An explicit `--db` hard-fails on a
    // projection error (the file is already durable, then nonzero); the default
    // target soft-degrades on an infra failure (the decision FILE is the
    // authoritative portable record per ADR 027). NOTE: a soft-degrade (or `--no-db`)
    // leaves the typed `operator_decisions` row absent for now — but `db import`
    // reconstructs it: it re-derives the audit row AND rebuilds the typed
    // `operator_decisions` row from the decision audit's full-redaction payload (v1 M2a
    // R1 P1), AFTER importing work events so a gate/conflict `--ref` resolves (R2 P4).
    // So a file-first decision fully recovers its live surface on the next `db import`.
    // This matches the M1 report/audit file-first recovery contract (DB = live
    // convenience, file = truth, import reconciles).
    // `projected_db` is Some(db_path) ONLY when the typed `operator_decisions` row
    // actually landed — the optional notify below needs that row to record its
    // outcome on. When notify was requested and this is None (a soft-degrade), the
    // notify leg below fails LOUD rather than dropping the requested send silently.
    let mut projected_db: Option<PathBuf> = None;
    if let Some((db_path, explicit)) = target.into_path_and_mode() {
        let result = crate::db::project_decision(&db_path, &common.root, &record, &decision);
        if explicit {
            result?;
            projected_db = Some(db_path);
        } else if let Err(error) = result {
            eprintln!(
                "warning: DB projection skipped (decision file written): {}",
                error.message
            );
        } else {
            projected_db = Some(db_path);
        }
    }

    // ADR 034 D7 + Codex C5: the decision record is now durable. When --retain-custody
    // was requested, retain the FULL decision payload as ciphertext in the custody_vault
    // BEFORE the optional notify hop. Reuse the EXACT bytes the decision audit hashed —
    // `audit_args.payload` (= `decision.to_storage()` computed above), never a re-derive —
    // so the recorded payload_hash and the ciphertext bind identical bytes. A retention
    // failure is ALWAYS LOUD (nonzero): the record is written but custody is NOT retained.
    // Per C5: on that failure we RETURN here and SKIP the notify entirely — the requested
    // custody failed, so we do not proceed to notify a peer. (`--no-db` + retain was
    // already rejected up front, so the DB target is resolvable here.)
    if common.retain_custody {
        let payload_bytes = audit_args
            .payload
            .as_deref()
            .expect("decision audit always carries an inline --payload (decision.to_storage)")
            .as_bytes();
        crate::audit::retain_custody_for(
            common.db.as_deref(),
            common.no_db,
            common.custody_key_file.as_deref(),
            &record,
            payload_bytes,
        )
        .map_err(|error| {
            CliError::failure(format!(
                "{}; record written but custody NOT retained: {}",
                audit_path.display(),
                error.message
            ))
        })?;
    }

    // The decision is now durable. The optional notification (ADR 033 D4 / C4=b) is a
    // SEPARATE audited send that happens AFTER durability and records its outcome on
    // the typed `operator_decisions` row — so it can only run when that row actually
    // landed (`projected_db` is Some, the C4=b path). A notify failure NEVER rolls
    // back the decision and NEVER fabricates a `sent` audit — it records the failure
    // on operator_decisions ONLY (notification_status=failed + error), then exits
    // nonzero so the operator knows the recipient was not reached.
    //
    // If notify was requested (both --notify-pane/--notify-to present, paired by
    // clap) but the DEFAULT projection SOFT-DEGRADED (`projected_db` is None — an
    // infra failure left the typed row absent), we must NOT silently skip the
    // requested send: the decision is durable, but the notify could not be honored.
    // Fail LOUD (nonzero) so the dropped action is visible; the operator can retry the
    // notify once the DB is healthy, or `db import` reconciles the decision audit.
    // (`--no-db` + notify was already rejected up front, so reaching here with notify
    // requested + None means a genuine soft-degrade.)
    if let (Some(notify_pane), Some(notify_to)) = (&common.notify_pane, &common.notify_to) {
        match &projected_db {
            Some(db_path) => {
                notify_decision(db_path, common, &record, &decision, notify_pane, notify_to)?;
            }
            None => {
                return Err(CliError::failure(format!(
                    "decision recorded to {}; notification NOT attempted: live DB \
                     projection unavailable (the decision is durable — retry the notify \
                     once the DB is healthy, or db import will reconcile)",
                    audit_path.display()
                )));
            }
        }
    }

    println!("{}", audit_path.display());
    Ok(())
}

/// Perform the optional decision notification (ADR 033 D4 / C4=b): a SEPARATE
/// audited `send herdr` (ADR 029) of the durable decision to `notify_pane`, then
/// record the outcome on the typed `operator_decisions` row.
///
/// Honesty contract (the C4=b core): on transport SUCCESS the audited send already
/// wrote the REAL `delivery_status=sent` proof (keyed by the notification mid), so
/// we link that exact row. On transport FAILURE the send wrote NO audit at all — we
/// record `notification_status=failed` + the error on the decision row ONLY (never
/// a fabricated `sent`, never a failed audit row) and surface the failure to the
/// caller. Either way the decision itself stays durable.
fn notify_decision(
    db_path: &std::path::Path,
    common: &Common,
    record: &crate::db::ImportedAuditRecord,
    decision: &Decision,
    notify_pane: &str,
    notify_to: &str,
) -> CliResult<()> {
    let notif_mid = crate::dashboard_write::mint_mid();
    let body = notification_body(decision);
    let send_args = crate::send_herdr::SendHerdrArgs {
        pane: notify_pane.to_string(),
        dry_run: false,
        herdr_bin: common.herdr_bin.clone(),
        session_id: Some(common.session_id.clone()),
        no_audit: false,
        root: common.root.clone(),
        // ADR 029 C5: the operator originated this notification send.
        command_origin: "operator".to_string(),
        payload_redaction_policy: "full".to_string(),
        sensitive_category: None,
        // Notify records its outcome on the decision row, so it shares the decision's
        // projected DB. (db_path is the projected target; --no-db never reaches here.)
        db: Some(db_path.to_path_buf()),
        no_db: false,
        // The notification send never retains custody: it is a separate peer message,
        // not where the decision's payload is retained (decide's own --retain-custody
        // is wired on the decision record itself, not on this notify hop).
        retain_custody: false,
        custody_key_file: None,
        compose: crate::compose::ComposeArgs {
            profile: None,
            from: Some("operator:cli".to_string()),
            to: Some(notify_to.to_string()),
            mid: Some(notif_mid.clone()),
            // ADR 003: the notification is the operator ANSWERing the decision (the
            // gate/conflict/mode question), threaded to the decision proof via `re`.
            // `answer` requires only `re` (set below) — no `--due`, which a decision
            // legitimately lacks.
            message_type: Some("answer".to_string()),
            shorthand: None,
            // The decision's identity (its proof mid) so the notification threads to it.
            r#ref: Some(record.mid.clone()),
            re: Some(record.mid.clone()),
            due: None,
            mode: None,
            transport: None,
            body: Some(body),
            body_file: None,
            field: Vec::new(),
            var: Vec::new(),
        },
    };

    match crate::send_herdr::run(send_args) {
        // Transport succeeded: link the REAL sent audit the audited send just wrote
        // (resolved by the notification mid). Never fabricate a proof.
        Ok(()) => crate::db::update_decision_notification(
            db_path,
            &record.audit_id,
            "sent",
            Some(&notif_mid),
            None,
        ),
        // Transport failed: the send wrote NO audit. Record the failure on the
        // decision row ONLY (status=failed + error, audit_id stays NULL), then exit
        // nonzero. The decision is already durable; we do NOT retry or roll back.
        Err(error) => {
            crate::db::update_decision_notification(
                db_path,
                &record.audit_id,
                "failed",
                None,
                Some(&error.message),
            )?;
            Err(CliError::with_code(
                error.code,
                format!("decision recorded; notification failed: {}", error.message),
            ))
        }
    }
}

/// A short human-readable notification body summarizing the decision (ADR 003
/// answer/request-action body). The decision is rebuilt from the in-hand value, so
/// no DB read-back is needed (`Decision::from_storage` stays unused here).
fn notification_body(decision: &Decision) -> String {
    match decision {
        Decision::Gate {
            target_work_event_id,
            verdict,
            ..
        } => format!("operator gate decision: {verdict} on work_event {target_work_event_id}"),
        Decision::Conflict {
            target_work_event_id,
            resolution,
            ..
        } => format!(
            "operator conflict resolution: {resolution} on work_event {target_work_event_id}"
        ),
        Decision::Mode { mode_to } => format!("operator mode switch: {mode_to}"),
        Decision::Interrupt { reason } => match reason {
            Some(reason) => format!("operator interrupt: {reason}"),
            None => "operator interrupt".to_string(),
        },
        Decision::Redirect {
            target_agent,
            reason,
        } => match reason {
            Some(reason) => format!("operator redirect to {target_agent}: {reason}"),
            None => format!("operator redirect to {target_agent}"),
        },
    }
}