req-cli 0.1.2

Managed requirements CLI for LLM agents and humans
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
// Implements REQ-0002 (git-diffable JSON), REQ-0003 (integrity hash),
// REQ-0004 (in-file warning + instructions), REQ-0019 (atomic writes),
// REQ-0062 (advisory file lock around mutation sequences).
// Discharges REQ-0020 (constraint: agents shall not edit project.req
// directly) by making the integrity hash the enforcement mechanism — any
// direct edit invalidates it and load_with_options refuses to read.
use anyhow::{anyhow, Context, Result};
use fs2::FileExt;
use serde_json::{json, Map, Value};
use sha2::{Digest, Sha256};
use std::fs;
use std::path::{Path, PathBuf};

use crate::model::Project;

pub const FORMAT_TAG: &str = "req-v1";
pub const FORMAT_TAG_DIR: &str = "req-v1-dir";

/// REQ-0075: the on-disk shape. `Single` is one JSON file at `path`.
/// `Directory` is a folder at `path` containing `index.req` and a
/// `requirements/REQ-NNNN.req` per requirement.
pub enum Layout {
    Single,
    Directory,
}

pub fn detect_layout(path: &Path) -> Layout {
    if path.is_dir() {
        Layout::Directory
    } else {
        Layout::Single
    }
}
pub const WARNING_HEADLINE: &str = "DO NOT EDIT THIS FILE BY HAND. Managed by the `req` CLI.";

pub fn instructions_block() -> Vec<String> {
    vec![
        "DO NOT EDIT THIS FILE BY HAND.".into(),
        "".into(),
        "This file is the source of truth for a managed requirements project. It is".into(),
        "git-diffable so humans can review changes in pull requests, but every".into(),
        "mutation must go through the `req` CLI so that best-practice validation".into(),
        "runs (atomic statements, modal verbs, acceptance criteria, no weasel words,".into(),
        "no broken links, etc.).".into(),
        "".into(),
        "Integrity: the `_integrity` field is a SHA-256 of the canonical payload.".into(),
        "If you edit this file directly the hash will no longer match and the CLI".into(),
        "will refuse to read it. To recover after an intentional manual edit:".into(),
        "  req repair --confirm-direct-edit".into(),
        "".into(),
        "Common commands:".into(),
        "  req init -n <name>                         create a new project".into(),
        "  req add                                    interactive add (recommended)".into(),
        "  req list [--status ...] [--kind ...]       table of requirements".into(),
        "  req show REQ-0001                          full detail for one".into(),
        "  req update REQ-0001 --status approved --reason \"team review\"".into(),
        "  req link REQ-0002 REQ-0001 -k parent       hierarchy / traceability".into(),
        "  req validate                               run rules across the project".into(),
        "  req export -f markdown -o reqs.md          publish".into(),
        "  req tui                                    interactive terminal browser".into(),
        "  req help <section>                         structured help; try: overview,".into(),
        "                                             concepts, best-practice, workflow,".into(),
        "                                             file-format, agents, export".into(),
        "".into(),
        "Agents: never edit this file. Drive `req` with subcommands, or use `req mcp`".into(),
        "(when available) to manage requirements through the JSON-RPC interface.".into(),
    ]
}

pub fn resolve_path(explicit: &Option<PathBuf>) -> PathBuf {
    if let Some(p) = explicit {
        return p.clone();
    }
    PathBuf::from("project.req")
}

/// On-disk format is pretty-printed JSON so the file is git-diffable.
/// Three reserved top-level fields gate edits:
///   _warning   — visible notice that this file is CLI-managed
///   _format    — schema tag, "req-v1"
///   _integrity — sha256 of the canonical payload (everything except _warning
///                and _integrity itself). Any direct edit changes the payload
///                and makes the hash mismatch.
pub fn save(path: &Path, project: &Project) -> Result<()> {
    match detect_layout(path) {
        Layout::Directory => return save_directory(path, project),
        Layout::Single => {}
    }
    let payload = serde_json::to_value(project).context("serialize project")?;
    let mut root = Map::new();
    root.insert("_warning".into(), Value::String(WARNING_HEADLINE.into()));
    root.insert(
        "_instructions".into(),
        Value::Array(
            instructions_block()
                .into_iter()
                .map(Value::String)
                .collect(),
        ),
    );
    root.insert("_format".into(), Value::String(FORMAT_TAG.into()));
    root.insert("_integrity".into(), Value::String(integrity_hash(&payload)));
    if let Value::Object(map) = payload {
        for (k, v) in map {
            root.insert(k, v);
        }
    } else {
        return Err(anyhow!("project did not serialize to a JSON object"));
    }

    if let Some(parent) = path.parent() {
        if !parent.as_os_str().is_empty() {
            fs::create_dir_all(parent).ok();
        }
    }
    let tmp = path.with_extension("req.tmp");
    let s = serde_json::to_string_pretty(&Value::Object(root))?;
    fs::write(&tmp, s)?;
    fs::rename(&tmp, path).with_context(|| format!("rename to {}", path.display()))?;
    Ok(())
}

pub fn load(path: &Path) -> Result<Project> {
    load_with_options(path, false)
}

/// `force` skips the integrity check — used by `req repair`.
pub fn load_with_options(path: &Path, force: bool) -> Result<Project> {
    if path.is_dir() {
        return load_directory(path, force);
    }
    let s = fs::read_to_string(path)
        .with_context(|| format!("open {} (run `req init` first?)", path.display()))?;
    let mut root: Map<String, Value> = serde_json::from_str(&s)
        .with_context(|| format!("{} is not valid JSON", path.display()))?;

    match root.get("_format").and_then(|v| v.as_str()) {
        Some(FORMAT_TAG) => {}
        Some(other) => {
            // Order matters for the hint: legacy "req-v0" etc would be older;
            // anything else we don't know is treated as newer.
            let is_older = other < FORMAT_TAG;
            let hint = if is_older {
                "run `req migrate` to upgrade the file in place (a backup is written)"
            } else {
                "upgrade the `req` binary — this file uses a newer format than this binary understands"
            };
            return Err(anyhow!(
                "unsupported _format: {} (this binary speaks {}). {}",
                other,
                FORMAT_TAG,
                hint
            ));
        }
        None => return Err(anyhow!("not a .req file: missing _format field")),
    }

    let stored_hash = root
        .remove("_integrity")
        .and_then(|v| v.as_str().map(|s| s.to_string()))
        .ok_or_else(|| anyhow!("missing _integrity field"))?;
    root.remove("_warning");
    root.remove("_instructions");
    root.remove("_format");

    let payload = Value::Object(root);
    let actual = integrity_hash(&payload);
    if !force && actual != stored_hash {
        return Err(anyhow!(
            "integrity check failed for {} — file appears to have been edited \
             directly.\n\nIf the changes are intentional, review them with `git diff` \
             and then run:\n  req repair --confirm-direct-edit\n\nOtherwise restore \
             from version control.",
            path.display()
        ));
    }
    let project: Project = serde_json::from_value(payload).context("deserialize project")?;
    Ok(project)
}

pub fn load_resolved(p: &Option<PathBuf>) -> Result<(PathBuf, Project)> {
    let path = resolve_path(p);
    let project = load(&path)?;
    Ok((path, project))
}

/// REQ-0062: exclusive advisory lock around a load-modify-save cycle.
/// Lock lives on a sidecar `<path>.lock` so it doesn't fight the
/// temp-and-rename save pattern. Drop the returned guard to release.
/// Times out after `LOCK_TIMEOUT_SECS` seconds with a clear error.
pub struct LockGuard {
    file: Option<std::fs::File>,
    // Path retained for diagnostics; the sidecar is NOT deleted on drop.
    // See the Drop impl for why.
    #[allow(dead_code)]
    path: PathBuf,
}

impl Drop for LockGuard {
    fn drop(&mut self) {
        if let Some(f) = self.file.take() {
            let _ = f.unlock();
        }
        // Intentionally do NOT remove the sidecar lock file. On Windows,
        // deleting the lock file after unlock — while other processes are
        // mid-acquire on the same path — lets a waiter open a fresh file
        // (new inode) at the same path while the original is being torn
        // down. Two processes can then hold "the lock" on what are
        // technically two different inodes that share a path, producing
        // the classic lost-update we saw in CI on
        // req_0062_five_concurrent_adds. Keeping the sidecar persistent
        // makes the inode stable; both fs2 (Unix flock) and Windows
        // LockFileEx behave correctly when every contender opens the
        // same underlying file.
        //
        // The sidecar is .gitignored so it doesn't end up in commits.
    }
}

const LOCK_TIMEOUT_SECS: u64 = 30;

pub fn acquire_lock(project_path: &Path) -> Result<LockGuard> {
    let lock_path = lock_sidecar(project_path);
    if let Some(parent) = lock_path.parent() {
        if !parent.as_os_str().is_empty() {
            fs::create_dir_all(parent).ok();
        }
    }
    let file = std::fs::OpenOptions::new()
        .read(true)
        .write(true)
        .create(true)
        .truncate(false)
        .open(&lock_path)
        .with_context(|| format!("open lock file {}", lock_path.display()))?;
    let deadline = std::time::Instant::now() + std::time::Duration::from_secs(LOCK_TIMEOUT_SECS);
    loop {
        match file.try_lock_exclusive() {
            Ok(()) => {
                return Ok(LockGuard {
                    file: Some(file),
                    path: lock_path,
                })
            }
            Err(_) if std::time::Instant::now() >= deadline => {
                return Err(anyhow!(
                    "could not acquire {} within {}s — another req process is mutating the project",
                    lock_path.display(),
                    LOCK_TIMEOUT_SECS,
                ));
            }
            Err(_) => std::thread::sleep(std::time::Duration::from_millis(50)),
        }
    }
}

fn lock_sidecar(project_path: &Path) -> PathBuf {
    let mut p = project_path.to_path_buf();
    let new_name = match p.file_name().and_then(|s| s.to_str()) {
        Some(n) => format!(".{}.lock", n),
        None => ".project.req.lock".into(),
    };
    p.set_file_name(new_name);
    p
}

/// Load the project under an exclusive lock; the returned guard MUST be
/// held until `save` returns. Use this in every mutation command site so
/// concurrent `req add` / `req update` cannot interleave their reads.
pub fn load_for_mutation(p: &Option<PathBuf>) -> Result<(PathBuf, Project, LockGuard)> {
    let path = resolve_path(p);
    let guard = acquire_lock(&path)?;
    let project = load(&path)?;
    Ok((path, project, guard))
}

// ---------- REQ-0075: directory-backed layout ----------
//
// Layout:
//   <root>/
//     index.req                  — project metadata + _format=req-v1-dir +
//                                  _integrity over the whole directory
//     requirements/REQ-NNNN.req  — one requirement per file (no per-file hash)
//
// The directory's _integrity covers: canonical JSON of the project minus
// the requirements map, concatenated with canonical JSON of each
// requirement file in sorted-ID order. Any change anywhere bumps the hash.

pub fn save_directory(root: &Path, project: &Project) -> Result<()> {
    fs::create_dir_all(root).with_context(|| format!("create {}", root.display()))?;
    let reqs_dir = root.join("requirements");
    fs::create_dir_all(&reqs_dir).with_context(|| format!("create {}", reqs_dir.display()))?;

    // Write each requirement to its own file (atomic per file).
    for (id, req) in &project.requirements {
        let p = reqs_dir.join(format!("{}.req", id));
        let body = serde_json::to_string_pretty(req)?;
        let tmp = p.with_extension("req.tmp");
        fs::write(&tmp, body)?;
        fs::rename(&tmp, &p)?;
    }
    // Remove any per-requirement files that are no longer in the project
    // (e.g. after a hard-delete).
    if let Ok(entries) = fs::read_dir(&reqs_dir) {
        for e in entries.flatten() {
            let name = e.file_name();
            let name_s = name.to_string_lossy();
            if let Some(stem) = name_s.strip_suffix(".req") {
                if !project.requirements.contains_key(stem) {
                    let _ = fs::remove_file(e.path());
                }
            }
        }
    }

    // Compute directory integrity hash and write index.
    let hash = directory_integrity(project)?;
    let mut root_obj = serde_json::Map::new();
    root_obj.insert("_warning".into(), Value::String(WARNING_HEADLINE.into()));
    root_obj.insert(
        "_instructions".into(),
        Value::Array(
            instructions_block()
                .into_iter()
                .map(Value::String)
                .collect(),
        ),
    );
    root_obj.insert("_format".into(), Value::String(FORMAT_TAG_DIR.into()));
    root_obj.insert("_integrity".into(), Value::String(hash));
    root_obj.insert("name".into(), Value::String(project.name.clone()));
    root_obj.insert("created".into(), serde_json::to_value(project.created)?);
    root_obj.insert("updated".into(), serde_json::to_value(project.updated)?);
    root_obj.insert("next_id".into(), Value::Number(project.next_id.into()));
    root_obj.insert(
        "requirement_ids".into(),
        Value::Array(
            project
                .requirements
                .keys()
                .map(|k| Value::String(k.clone()))
                .collect(),
        ),
    );

    let index_path = root.join("index.req");
    let body = serde_json::to_string_pretty(&Value::Object(root_obj))?;
    let tmp = index_path.with_extension("req.tmp");
    fs::write(&tmp, body)?;
    fs::rename(&tmp, &index_path)?;
    Ok(())
}

pub fn load_directory(root: &Path, force: bool) -> Result<Project> {
    let index_path = root.join("index.req");
    let s = fs::read_to_string(&index_path)
        .with_context(|| format!("read {}", index_path.display()))?;
    let mut root_obj: serde_json::Map<String, Value> = serde_json::from_str(&s)
        .with_context(|| format!("{} is not valid JSON", index_path.display()))?;

    match root_obj.get("_format").and_then(|v| v.as_str()) {
        Some(FORMAT_TAG_DIR) => {}
        Some(other) => return Err(anyhow!("unsupported _format in directory index: {}", other)),
        None => return Err(anyhow!("not a directory-layout project: missing _format")),
    }
    let stored_hash = root_obj
        .remove("_integrity")
        .and_then(|v| v.as_str().map(|s| s.to_string()))
        .ok_or_else(|| anyhow!("missing _integrity in directory index"))?;

    // Read all requirement files
    let reqs_dir = root.join("requirements");
    let mut requirements = std::collections::BTreeMap::new();
    if let Ok(entries) = fs::read_dir(&reqs_dir) {
        for e in entries.flatten() {
            let p = e.path();
            if p.extension().and_then(|s| s.to_str()) != Some("req") {
                continue;
            }
            let body = fs::read_to_string(&p)?;
            let req: crate::model::Requirement =
                serde_json::from_str(&body).with_context(|| format!("parse {}", p.display()))?;
            requirements.insert(req.id.clone(), req);
        }
    }

    let project = Project {
        name: root_obj
            .get("name")
            .and_then(|v| v.as_str())
            .unwrap_or("")
            .to_string(),
        created: serde_json::from_value(root_obj.remove("created").unwrap_or(Value::Null))?,
        updated: serde_json::from_value(root_obj.remove("updated").unwrap_or(Value::Null))?,
        next_id: root_obj
            .get("next_id")
            .and_then(|v| v.as_u64())
            .unwrap_or(1) as u32,
        requirements,
    };

    if !force {
        let actual = directory_integrity(&project)?;
        if actual != stored_hash {
            return Err(anyhow!(
                "integrity check failed for directory-layout project at {} — files appear edited.\n\
                 If intentional, run: req repair --confirm-direct-edit",
                root.display()
            ));
        }
    }
    Ok(project)
}

fn directory_integrity(project: &Project) -> Result<String> {
    // Hash: canonical JSON of (next_id, name, created, updated) followed
    // by canonical JSON of each requirement in sorted-ID order.
    let mut hasher = Sha256::new();
    let header = serde_json::json!({
        "name": project.name,
        "next_id": project.next_id,
        "created": project.created,
        "updated": project.updated,
    });
    hasher.update(canonical_json(&header).as_bytes());
    for req in project.requirements.values() {
        let v = serde_json::to_value(req)?;
        hasher.update(canonical_json(&v).as_bytes());
    }
    Ok(format!("sha256:{}", hex::encode(hasher.finalize())))
}

fn integrity_hash(payload: &Value) -> String {
    let canonical = canonical_json(payload);
    let mut hasher = Sha256::new();
    hasher.update(canonical.as_bytes());
    format!("sha256:{}", hex::encode(hasher.finalize()))
}

/// Stable canonical JSON: object keys sorted recursively, no whitespace.
fn canonical_json(v: &Value) -> String {
    match v {
        Value::Object(map) => {
            let mut keys: Vec<&String> = map.keys().collect();
            keys.sort();
            let mut out = String::from("{");
            for (i, k) in keys.iter().enumerate() {
                if i > 0 {
                    out.push(',');
                }
                out.push_str(&serde_json::to_string(k).unwrap());
                out.push(':');
                out.push_str(&canonical_json(&map[*k]));
            }
            out.push('}');
            out
        }
        Value::Array(arr) => {
            let mut out = String::from("[");
            for (i, item) in arr.iter().enumerate() {
                if i > 0 {
                    out.push(',');
                }
                out.push_str(&canonical_json(item));
            }
            out.push(']');
            out
        }
        _ => serde_json::to_string(v).unwrap(),
    }
}

#[allow(dead_code)]
pub fn _force_json() -> Value {
    json!(null)
}