zynk 0.3.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
use crate::profile::load_profile;
use crate::{CliError, CliResult};
use clap::Args;
use fs2::FileExt;
use rand::{rngs::OsRng, Rng};
use sha2::{Digest, Sha256};
use std::collections::HashSet;
use std::fs::{self, OpenOptions};
use std::io::{Read, Seek, SeekFrom, Write};
use std::path::PathBuf;

#[derive(Debug, Args)]
pub struct AuditArgs {
    #[arg(long)]
    pub profile: Option<PathBuf>,
    #[arg(
        long,
        default_value = "outputs",
        help = "runtime outputs root; pass <project>/outputs to write <project>/outputs/sessions/..."
    )]
    pub root: PathBuf,
    #[arg(long)]
    pub session_id: String,
    #[arg(long)]
    pub audit_id: Option<String>,
    #[arg(long)]
    pub previous_audit_id: Option<String>,
    #[arg(long)]
    pub timestamp: Option<String>,
    #[arg(
        long,
        help = "optional RFC3339 UTC deadline/expected-by for this record (ADR 027); advisory only"
    )]
    pub due: Option<String>,
    #[arg(long)]
    pub source_agent: String,
    #[arg(long)]
    pub source_address: String,
    #[arg(long)]
    pub target_agent: String,
    #[arg(long)]
    pub target_address: String,
    #[arg(long)]
    pub transport: String,
    #[arg(long)]
    pub workspace_id: String,
    #[arg(long)]
    pub transport_thread_id: Option<String>,
    #[arg(long)]
    pub mid: String,
    #[arg(long = "type")]
    pub record_type: String,
    #[arg(long)]
    pub mode: Option<String>,
    #[arg(long)]
    pub r#ref: Option<String>,
    #[arg(long)]
    pub re: Option<String>,
    #[arg(long, value_parser = ["agent", "operator", "helper-tool", "unknown"])]
    pub command_origin: String,
    #[arg(long)]
    pub payload: Option<String>,
    #[arg(long)]
    pub payload_file: Option<PathBuf>,
    #[arg(long, default_value = "hash-only")]
    pub payload_redaction_policy: String,
    #[arg(long)]
    pub payload_ref: Option<String>,
    #[arg(long)]
    pub sensitive_category: Option<String>,
    #[arg(long, default_value_t = 12)]
    pub excerpt_chars: usize,
    #[arg(
        long,
        help = "delivery proof state; use drafted for message-shaped text that was not sent"
    )]
    pub delivery_status: String,
    #[arg(long)]
    pub observed_by: String,
    #[arg(long, value_parser = ["transport", "agent", "operator", "helper-tool"])]
    pub verified_by: String,
    #[arg(
        long,
        help = "live DB path; when set (or .zynk/zynk.db exists) the record is projected into SQLite (ADR 027)"
    )]
    pub db: Option<PathBuf>,
    #[arg(
        long,
        help = "force file-only; skip the DB projection even if a DB exists"
    )]
    pub no_db: bool,
}

pub fn run(args: AuditArgs) -> CliResult<()> {
    let profile = load_profile(args.profile.as_deref())?;
    if args.payload.is_some() == args.payload_file.is_some() {
        return Err(CliError::usage(
            "exactly one of --payload or --payload-file is required",
        ));
    }
    if args.excerpt_chars < 1 {
        return Err(CliError::usage("--excerpt-chars must be >= 1"));
    }
    if !profile
        .audit
        .delivery_status_enum
        .contains(&args.delivery_status)
    {
        return Err(CliError::usage(format!(
            "invalid delivery status: {}",
            args.delivery_status
        )));
    }
    if args.delivery_status == "sent" && args.verified_by == "agent" {
        return Err(CliError::usage(
            "delivery_status=sent requires transport, helper-tool, or operator verification",
        ));
    }
    // ADR 027 C4: validate --due with the real RFC3339 parser at the boundary
    // (the v5 GLOB trigger is only a defense-in-depth shape guard). Fail loud on
    // a malformed or impossible value rather than letting it reach an artifact.
    if let Some(due) = &args.due {
        if crate::timestamp::canonicalize(due).is_none() {
            return Err(CliError::usage(format!(
                "invalid due timestamp: {due} (expected RFC3339, e.g. 2026-06-01T12:00:00Z)"
            )));
        }
    }
    // ADR 027 C2/R1 P1: real-parser validate --timestamp BEFORE any file write.
    // A valid offset is preserved raw in the artifact (the DB projection
    // canonicalizes); a malformed or calendar-invalid value is rejected here.
    if let Some(timestamp) = &args.timestamp {
        if crate::timestamp::canonicalize(timestamp).is_none() {
            return Err(CliError::usage(format!(
                "invalid timestamp: {timestamp} (expected RFC3339, e.g. 2026-05-29T12:00:00Z)"
            )));
        }
    }
    if !profile
        .audit
        .redaction_policy_enum
        .contains(&args.payload_redaction_policy)
    {
        return Err(CliError::usage(format!(
            "invalid redaction policy: {}",
            args.payload_redaction_policy
        )));
    }

    let audit_path = args
        .root
        .join("sessions")
        .join(&args.session_id)
        .join("audit.md");
    if let Some(parent) = audit_path.parent() {
        fs::create_dir_all(parent).map_err(|error| {
            CliError::failure(format!("failed to create {}: {error}", parent.display()))
        })?;
    }

    let mut handle = OpenOptions::new()
        .read(true)
        .write(true)
        .create(true)
        .truncate(false)
        .open(&audit_path)
        .map_err(|error| {
            CliError::failure(format!("failed to open {}: {error}", audit_path.display()))
        })?;
    handle.lock_exclusive().map_err(|error| {
        CliError::failure(format!("failed to lock {}: {error}", audit_path.display()))
    })?;
    let result = write_locked_record(&args, &profile, &mut handle);
    let unlock_result = handle.unlock();
    if let Err(error) = unlock_result {
        return Err(CliError::failure(format!(
            "failed to unlock {}: {error}",
            audit_path.display()
        )));
    }
    let record = result?;

    // ADR 027: file-first, then synchronous DB projection (presence-gated). Done
    // after unlocking — never hold the file lock during DB I/O. A projection
    // gap or failure is an infra soft-degrade (warn; file written; `db import`
    // reconciles). Invariants were validated above before the file was written.
    if let Some(db_path) = crate::db::resolve_projection_db(args.db.as_deref(), args.no_db) {
        match crate::db::project_audit(&db_path, &args.root, &record) {
            Ok(crate::db::LiveAuditProjection::Gap { reason }) => eprintln!(
                "warning: audit DB projection gap (file written; db import will reconcile): {reason}"
            ),
            Ok(_) => {}
            Err(error) => eprintln!(
                "warning: audit DB projection skipped (file written): {}",
                error.message
            ),
        }
    }

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

fn write_locked_record(
    args: &AuditArgs,
    profile: &crate::profile::Profile,
    handle: &mut std::fs::File,
) -> CliResult<crate::db::ImportedAuditRecord> {
    handle
        .seek(SeekFrom::Start(0))
        .map_err(|error| CliError::failure(format!("failed to read audit file: {error}")))?;
    let mut existing_content = String::new();
    handle
        .read_to_string(&mut existing_content)
        .map_err(|error| CliError::failure(format!("failed to read audit file: {error}")))?;
    let existing_ids = audit_ids_from_text(&existing_content);
    let existing_id_set = existing_ids.iter().cloned().collect::<HashSet<_>>();
    let audit_id = if let Some(audit_id) = &args.audit_id {
        if existing_id_set.contains(audit_id) {
            return Err(CliError::usage(format!("duplicate audit_id: {audit_id}")));
        }
        audit_id.clone()
    } else {
        generate_audit_id(&existing_id_set)?
    };
    let previous_audit_id = args
        .previous_audit_id
        .clone()
        .unwrap_or_else(|| last_audit_id(&existing_ids));
    let (record_text, imported) = render_record(args, profile, &previous_audit_id, &audit_id)?;

    handle
        .seek(SeekFrom::End(0))
        .map_err(|error| CliError::failure(format!("failed to append audit file: {error}")))?;
    if existing_content.is_empty() {
        write!(
            handle,
            "# Audit Trail: {}\n\nsession_id: {}\n\n## Records\n\n",
            args.session_id, args.session_id
        )
        .map_err(|error| CliError::failure(format!("failed to write audit header: {error}")))?;
    }
    writeln!(handle, "{record_text}")
        .map_err(|error| CliError::failure(format!("failed to write audit record: {error}")))?;
    Ok(imported)
}

fn render_record(
    args: &AuditArgs,
    profile: &crate::profile::Profile,
    previous_audit_id: &str,
    audit_id: &str,
) -> CliResult<(String, crate::db::ImportedAuditRecord)> {
    let mut policy = args.payload_redaction_policy.clone();
    if let Some(category) = &args.sensitive_category {
        if profile.audit.force_hash_only_categories.contains(category) {
            policy = "hash-only".to_string();
        }
    }
    let payload = payload_from_args(args)?;
    let payload_bytes = payload.as_bytes();
    let digest = Sha256::digest(payload_bytes);
    let timestamp = args
        .timestamp
        .clone()
        .unwrap_or_else(crate::timestamp::now_utc_seconds);
    let excerpt = payload_excerpt(&payload, args.excerpt_chars, &policy);
    // Canonicalize for the artifact (run() already rejected a malformed --due).
    let due = args
        .due
        .as_ref()
        .and_then(|due| crate::timestamp::canonicalize(due));
    let payload_hash = format!("sha256:{digest:x}");
    let content_size = payload_bytes.len();

    // Single source: the DB projection record is built from the SAME resolved
    // values the file is rendered from, so file and DB share one chain identity
    // (ADR 027 C6). previous_audit_id="none" means a chain head (NULL in the DB).
    let imported = crate::db::ImportedAuditRecord {
        audit_id: audit_id.to_string(),
        previous_audit_id: (previous_audit_id != "none").then(|| previous_audit_id.to_string()),
        timestamp: timestamp.clone(),
        source_agent_id: Some(args.source_agent.clone()),
        source_address: args.source_address.clone(),
        target_agent_id: Some(args.target_agent.clone()),
        target_address: args.target_address.clone(),
        transport: args.transport.clone(),
        workspace_id: args.workspace_id.clone(),
        session_id: args.session_id.clone(),
        mid: args.mid.clone(),
        record_type: args.record_type.clone(),
        command_origin: args.command_origin.clone(),
        mode: args.mode.clone(),
        r#ref: args.r#ref.clone(),
        re: args.re.clone(),
        payload_hash: payload_hash.clone(),
        payload_redaction_policy: policy.clone(),
        content_size: content_size as i64,
        delivery_status: args.delivery_status.clone(),
        observed_by: args.observed_by.clone(),
        verified_by: args.verified_by.clone(),
        due: due.clone(),
    };

    let mut fields: Vec<(String, String)> = vec![
        ("audit_id".to_string(), audit_id.to_string()),
        (
            "previous_audit_id".to_string(),
            previous_audit_id.to_string(),
        ),
        ("timestamp".to_string(), timestamp),
        ("source_agent".to_string(), args.source_agent.clone()),
        ("source_address".to_string(), args.source_address.clone()),
        ("target_agent".to_string(), args.target_agent.clone()),
        ("target_address".to_string(), args.target_address.clone()),
        ("transport".to_string(), args.transport.clone()),
        ("workspace_id".to_string(), args.workspace_id.clone()),
        ("session_id".to_string(), args.session_id.clone()),
        ("mid".to_string(), args.mid.clone()),
        ("type".to_string(), args.record_type.clone()),
        ("command_origin".to_string(), args.command_origin.clone()),
        ("payload_hash".to_string(), payload_hash),
        ("payload_redaction_policy".to_string(), policy),
        ("content_size".to_string(), content_size.to_string()),
        ("delivery_status".to_string(), args.delivery_status.clone()),
        ("observed_by".to_string(), args.observed_by.clone()),
        ("verified_by".to_string(), args.verified_by.clone()),
    ];
    for (key, value) in [
        ("transport_thread_id", args.transport_thread_id.as_ref()),
        ("mode", args.mode.as_ref()),
        ("ref", args.r#ref.as_ref()),
        ("re", args.re.as_ref()),
        ("due", due.as_ref()),
        ("payload_ref", args.payload_ref.as_ref()),
        ("payload_excerpt", excerpt.as_ref()),
    ] {
        if let Some(value) = value {
            fields.push((key.to_string(), value.clone()));
        }
    }

    let record = fields
        .into_iter()
        .map(|(key, value)| format!("{key}={value}"))
        .collect::<Vec<_>>()
        .join("\n");
    Ok((format!("```text\n{record}\n```"), imported))
}

fn payload_from_args(args: &AuditArgs) -> CliResult<String> {
    if let Some(path) = &args.payload_file {
        return fs::read_to_string(path).map_err(|error| {
            CliError::failure(format!(
                "failed to read payload file {}: {error}",
                path.display()
            ))
        });
    }
    Ok(args.payload.clone().unwrap_or_default())
}

fn payload_excerpt(payload: &str, chars: usize, policy: &str) -> Option<String> {
    match policy {
        "hash-only" => None,
        "full" => Some(payload.to_string()),
        _ => {
            let count = payload.chars().count();
            if count <= chars * 2 {
                Some(payload.to_string())
            } else {
                let start = payload.chars().take(chars).collect::<String>();
                let end = payload
                    .chars()
                    .rev()
                    .take(chars)
                    .collect::<String>()
                    .chars()
                    .rev()
                    .collect::<String>();
                Some(format!("{start}...{end}"))
            }
        }
    }
}

fn audit_ids_from_text(content: &str) -> Vec<String> {
    content
        .lines()
        .filter_map(|line| line.trim().strip_prefix("audit_id="))
        .filter(|id| {
            id.chars()
                .all(|ch| ch.is_ascii_lowercase() || ch.is_ascii_digit())
        })
        .map(str::to_string)
        .collect()
}

fn last_audit_id(existing_ids: &[String]) -> String {
    existing_ids
        .iter()
        .last()
        .cloned()
        .unwrap_or_else(|| "none".to_string())
}

fn generate_audit_id(existing_ids: &HashSet<String>) -> CliResult<String> {
    const ALPHABET: &[u8] = b"abcdefghijklmnopqrstuvwxyz0123456789";
    let mut rng = OsRng;
    for _ in 0..100 {
        let audit_id = (0..6)
            .map(|_| {
                let index = rng.gen_range(0..ALPHABET.len());
                ALPHABET[index] as char
            })
            .collect::<String>();
        if !existing_ids.contains(&audit_id) {
            return Ok(audit_id);
        }
    }
    Err(CliError::usage(
        "could not generate unique audit_id after 100 attempts",
    ))
}