req-cli 0.5.0-rc.7

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
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
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
// Implements REQ-0002 (git-diffable JSON), REQ-0003 (integrity hash),
// REQ-0004 (in-file warning + instructions), REQ-0022 (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-v4";
pub const FORMAT_TAG_DIR: &str = "req-v1-dir";

/// REQ-0141: monotonic schema-revision counter, written into every file's
/// hashed payload as `_schema_rev`. Bump this whenever the on-disk shape of
/// a record changes (a field added, renamed, or given new semantics) so a
/// binary that knows a lower revision refuses to *load* — and therefore
/// cannot save over — a file a newer binary wrote, rather than silently
/// dropping fields it cannot model. A file with no `_schema_rev` (written
/// before this guard existed) is treated as rev 0.
///
/// The guard fires on load, before the integrity check, mirroring how a
/// newer `_format` tag is rejected: refusing to read a file we don't fully
/// understand is safer than reading it, dropping the unknown parts, and
/// writing the loss back. `_schema_rev` lives *inside* the integrity payload
/// (not as a reserved meta key) so that an older binary which has no concept
/// of it still computes a matching hash — introducing the stamp does not
/// break the integrity check for existing readers.
///
/// Revision history:
///   1 — introduced the guard; baseline for the req-v3 shape that already
///       carries per-requirement `verification` (REQ-0139) and the
///       functional-safety artifacts (REQ-0134).
pub const SCHEMA_REV: u64 = 1;

/// REQ-0141: reject a payload whose `_schema_rev` is newer than this binary
/// understands, with a message that names both revisions and points at the
/// fix. Called on load, before the integrity check.
fn guard_schema_rev(map: &Map<String, Value>, path: &Path) -> Result<()> {
    let on_disk = map.get("_schema_rev").and_then(Value::as_u64).unwrap_or(0);
    if on_disk > SCHEMA_REV {
        return Err(anyhow!(
            "{} was written by a newer `req` (schema rev {}, this binary speaks \
             rev {}). Upgrade the binary — this version would drop fields it does \
             not understand.",
            path.display(),
            on_disk,
            SCHEMA_REV
        ));
    }
    Ok(())
}

/// 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 verification".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 conform                               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 s = to_canonical_json(project)?;
    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");
    fs::write(&tmp, s)?;
    fs::rename(&tmp, path).with_context(|| format!("rename to {}", path.display()))?;
    Ok(())
}

/// REQ-0207: render the canonical, integrity-signed single-file JSON form of a
/// project to a string, without touching the filesystem. This is exactly what
/// `save` writes for the single-file layout; factored out so the `req merge`
/// driver can serialise each side of a conflict as a self-contained, valid
/// `.req` document (so that once a human deletes the losing block and the
/// markers, the surviving block already carries a correct integrity hash).
pub fn to_canonical_json(project: &Project) -> Result<String> {
    let mut payload_map = match serde_json::to_value(project).context("serialize project")? {
        Value::Object(m) => m,
        _ => return Err(anyhow!("project did not serialize to a JSON object")),
    };
    // REQ-0141: `_schema_rev` is part of the *hashed* payload, not a reserved
    // key excluded from it. That is deliberate: a binary that does not know
    // the key still computes a matching integrity hash (it just treats the
    // key as ordinary content), so introducing the stamp does not break the
    // integrity check for an older reader. It also means the revision is
    // tamper-evident — a direct edit lowering it to dodge the guard trips the
    // hash.
    payload_map.insert("_schema_rev".into(), Value::Number(SCHEMA_REV.into()));
    let payload = Value::Object(payload_map);
    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"));
    }
    Ok(serde_json::to_string_pretty(&Value::Object(root))?)
}

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;
            // REQ-0122: auto-migrate older formats on first encounter when
            // a migration chain is registered. Opt out with
            // REQ_NO_AUTO_MIGRATE=1. Newer-than-current files always error
            // (no downgrade path).
            if is_older
                && std::env::var("REQ_NO_AUTO_MIGRATE").is_err()
                && has_migration_path(other, FORMAT_TAG)
            {
                eprintln!(
                    "req: auto-migrating {} from {} to {} (set REQ_NO_AUTO_MIGRATE=1 to opt out)",
                    path.display(),
                    other,
                    FORMAT_TAG
                );
                auto_migrate_in_place(path, &s)?;
                // Re-read after migration. The migration writes a sibling
                // backup and re-signs the file before we get here.
                let s2 = fs::read_to_string(path)
                    .with_context(|| format!("re-open {} after auto-migrate", path.display()))?;
                root = serde_json::from_str(&s2).with_context(|| {
                    format!("{} not valid JSON after auto-migrate", path.display())
                })?;
            } else {
                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")),
    }

    // REQ-0141: refuse a newer schema revision before doing anything else,
    // just like a newer _format above.
    guard_schema_rev(&root, path)?;

    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");
    // REQ-0141: `_schema_rev` stays in the hashed payload (see `save`), so it
    // is NOT removed before the integrity check — only afterwards, below.

    let mut payload = Value::Object(root);
    let actual = integrity_hash(&payload);
    // SR-0001: refuse to load a spec whose content fails its integrity hash.
    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()
        ));
    }
    // REQ-0141: strip the reserved `_schema_rev` only now (after hashing) so
    // the flatten catch-all on `Project` does not capture it as project data.
    if let Value::Object(m) = &mut payload {
        m.remove("_schema_rev");
    }
    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()));
    // REQ-0141: stamp the schema revision into the index (the directory
    // integrity hash is computed over the project, not this map, so the key
    // does not perturb it).
    root_obj.insert("_schema_rev".into(), Value::Number(SCHEMA_REV.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(),
        ),
    );
    // REQ-0135: persist the functional-safety artifacts in the index so a
    // directory-layout project does not silently drop them. Written only
    // when non-empty / non-default, so a project with no safety data keeps
    // a byte-identical index (and integrity hash) to before the feature.
    insert_safety_fields(&mut root_obj, project)?;

    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")),
    }
    // REQ-0141: refuse a newer schema revision recorded in the index.
    guard_schema_rev(&root_obj, &index_path)?;
    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,
        // REQ-0135: the functional-safety artifacts round-trip through the
        // index file (omitted when empty). Reading them here is what stops
        // a directory-layout project from silently dropping them on save.
        hazards: root_obj
            .remove("hazards")
            .and_then(|v| serde_json::from_value(v).ok())
            .unwrap_or_default(),
        safety_functions: root_obj
            .remove("safety_functions")
            .and_then(|v| serde_json::from_value(v).ok())
            .unwrap_or_default(),
        safety_requirements: root_obj
            .remove("safety_requirements")
            .and_then(|v| serde_json::from_value(v).ok())
            .unwrap_or_default(),
        next_haz_id: root_obj
            .get("next_haz_id")
            .and_then(|v| v.as_u64())
            .unwrap_or(1) as u32,
        next_sf_id: root_obj
            .get("next_sf_id")
            .and_then(|v| v.as_u64())
            .unwrap_or(1) as u32,
        next_sr_id: root_obj
            .get("next_sr_id")
            .and_then(|v| v.as_u64())
            .unwrap_or(1) as u32,
        purpose: root_obj
            .remove("_purpose")
            .and_then(|v| serde_json::from_value(v).ok()),
        config: root_obj
            .remove("_config")
            .and_then(|v| serde_json::from_value(v).ok()),
        // The directory index is reconstructed field-by-field rather than
        // via serde flatten, so top-level unknowns are not round-tripped
        // here (the single-file format is the one that needs REQ-0140's
        // catch-all). Requirement/safety-entity `extra` still round-trips
        // through their own per-file serialization.
        extra: Default::default(),
    };

    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 the header (name, next_id, created,
    // updated, plus any non-empty safety artifacts) followed by canonical
    // JSON of each requirement in sorted-ID order.
    let mut hasher = Sha256::new();
    let mut header = serde_json::Map::new();
    header.insert("name".into(), Value::String(project.name.clone()));
    header.insert("next_id".into(), Value::Number(project.next_id.into()));
    header.insert("created".into(), serde_json::to_value(project.created)?);
    header.insert("updated".into(), serde_json::to_value(project.updated)?);
    // REQ-0135: cover the safety artifacts in the directory hash, using
    // the same omit-when-empty rule as the index so the hash matches what
    // is persisted and existing safety-free projects are unaffected.
    insert_safety_fields(&mut header, project)?;
    hasher.update(canonical_json(&Value::Object(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())))
}

/// REQ-0135: serialise the functional-safety artifacts into a JSON map,
/// omitting empty maps and default (1) counters so a project with no
/// safety data is byte-identical to one written before the feature
/// existed. Shared by the directory index writer and the integrity hash
/// so the two never disagree.
fn insert_safety_fields(map: &mut Map<String, Value>, project: &Project) -> Result<()> {
    if !project.hazards.is_empty() {
        map.insert("hazards".into(), serde_json::to_value(&project.hazards)?);
        map.insert(
            "next_haz_id".into(),
            Value::Number(project.next_haz_id.into()),
        );
    }
    if !project.safety_functions.is_empty() {
        map.insert(
            "safety_functions".into(),
            serde_json::to_value(&project.safety_functions)?,
        );
        map.insert(
            "next_sf_id".into(),
            Value::Number(project.next_sf_id.into()),
        );
    }
    if !project.safety_requirements.is_empty() {
        map.insert(
            "safety_requirements".into(),
            serde_json::to_value(&project.safety_requirements)?,
        );
        map.insert(
            "next_sr_id".into(),
            Value::Number(project.next_sr_id.into()),
        );
    }
    Ok(())
}

/// REQ-0122: probe whether the migration registry can walk from
/// `from` to `to`. We don't apply the migration here — just answer
/// "is the path representable". Used by load() to decide whether to
/// auto-migrate or surface the manual-migrate hint.
fn has_migration_path(from: &str, to: &str) -> bool {
    use crate::migrations;
    let steps = migrations::registered_steps();
    let mut current = from.to_string();
    let mut seen = std::collections::HashSet::new();
    while current != to {
        if !seen.insert(current.clone()) {
            return false; // cycle
        }
        match steps.iter().find(|s| s.from == current) {
            Some(step) => current = step.to.to_string(),
            None => return false,
        }
    }
    true
}

/// REQ-0122: do the same work `req migrate` would do, in-process,
/// from a load() context. Writes a sibling backup, applies the
/// migration chain, re-signs the integrity hash, writes the file.
/// Errors propagate so an integrity-mismatch or missing-chain case
/// still surfaces to the user with a clear message.
fn auto_migrate_in_place(path: &Path, raw_before: &str) -> Result<()> {
    use crate::migrations;
    let mut root: Map<String, Value> = serde_json::from_str(raw_before)?;
    let detected: String = root
        .get("_format")
        .and_then(|v| v.as_str())
        .ok_or_else(|| anyhow!("not a .req file: missing _format"))?
        .to_string();
    let backup = path.with_extension(format!("req.bak-{}", detected));
    fs::copy(path, &backup).with_context(|| format!("write backup {}", backup.display()))?;

    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_before = Value::Object(root.clone());
    let computed = integrity_hash(&payload_before);
    if computed != stored_hash {
        return Err(anyhow!(
            "integrity check failed for {} before auto-migrate — run \
             `req repair --confirm-direct-edit` first, then re-run the \
             original command. Backup at {}.",
            path.display(),
            backup.display()
        ));
    }
    let (migrated, ended_at) = migrations::walk_chain(root, &detected, FORMAT_TAG)?;
    let final_payload = Value::Object(migrated);
    let new_hash = integrity_hash(&final_payload);
    let mut final_root: Map<String, Value> = match final_payload {
        Value::Object(m) => m,
        _ => unreachable!("walk_chain returns Object root"),
    };
    final_root.insert("_format".into(), Value::String(ended_at.clone()));
    final_root.insert("_integrity".into(), Value::String(new_hash));
    let serialised = serde_json::to_string_pretty(&Value::Object(final_root))?;
    fs::write(path, serialised).with_context(|| format!("write {}", path.display()))?;
    eprintln!(
        "req: auto-migrated → {} (backup at {})",
        ended_at,
        backup.display()
    );
    Ok(())
}

pub 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)
}