ccd-cli 1.0.0-beta.2

Bootstrap and validate Continuous Context Development repositories
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
pub(crate) const SURFACED_REFERENCE_EXTENSIONS: &[&str] = &[
    ".rs", ".md", ".toml", ".json", ".sh", ".yml", ".yaml", ".py", ".ts", ".tsx", ".go", ".txt",
    ".sql", ".rb", ".java", ".c", ".cpp", ".h", ".hpp", ".html", ".css", ".lock",
];

// NOTE: `CHANGELOG` was removed from this list (see ccd#585). Prose
// references to "the changelog" are almost always references to
// `CHANGELOG.md`, not to a bare extensionless file, and the bare form
// produced high-volume false positives at session start.
pub(crate) const SURFACED_EXTENSIONLESS_FILENAMES: &[&str] = &[
    "Dockerfile",
    "Makefile",
    "LICENSE",
    "COPYING",
    "NOTICE",
    "README",
    "CONTRIBUTING",
    "AUTHORS",
    "MAINTAINERS",
    "CODEOWNERS",
    "Gemfile",
    "Rakefile",
    "Procfile",
];

/// Repo path prefixes that authors use in prose to name an in-repo
/// location (`src/commands/host.rs`, `.github/workflows/...`). Used by
/// the strict unquoted-prose detector: unquoted slashed tokens must
/// begin with one of these (or an absolute / relative anchor) to be
/// treated as a path candidate.
const REPO_PATH_PREFIXES: &[&str] = &[
    "src/",
    "docs/",
    "tests/",
    "test/",
    "scripts/",
    "skills/",
    "specs/",
    "templates/",
    "examples/",
    "crates/",
    "benches/",
    "assets/",
    "migrations/",
    "lib/",
    "bin/",
    "cmd/",
    "pkg/",
    "internal/",
    "app/",
    "config/",
    ".github/",
    ".claude/",
    ".gemini/",
    ".agents/",
    ".ccd/",
    ".ccd-hosts/",
];

fn has_anchor_or_repo_prefix(token: &str) -> bool {
    if token.starts_with('/') || token.starts_with("./") || token.starts_with("../") {
        return true;
    }
    REPO_PATH_PREFIXES
        .iter()
        .any(|prefix| token.starts_with(prefix))
}

fn ends_with_known_extension(token: &str) -> bool {
    SURFACED_REFERENCE_EXTENSIONS
        .iter()
        .any(|ext| token.ends_with(ext))
}

/// Reject bare extension tokens (`.rs`, `.md`) that carry no filename
/// stem. Such tokens drop out of prose like "touch .rs files" and
/// were previously flagged as missing references.
fn has_nonempty_stem_before_extension(token: &str) -> bool {
    for ext in SURFACED_REFERENCE_EXTENSIONS {
        if let Some(stem) = token.strip_suffix(ext) {
            return !stem.is_empty() && stem.chars().any(|c| c != '/');
        }
    }
    true
}

fn contains_unresolved_placeholder(token: &str) -> bool {
    if token.contains("YYYY") || token.contains("MM-DD") {
        return true;
    }
    if token.contains("XXXX") {
        return true;
    }
    if contains_repeat_run_in_filename_context(token, b'N', 3) {
        return true;
    }
    let bytes = token.as_bytes();
    let digit_context = bytes.iter().any(|b| b.is_ascii_digit());
    if !digit_context {
        return false;
    }
    let mut i = 0;
    while i + 2 <= bytes.len() {
        if &bytes[i..i + 2] == b"XX" {
            let before = i.checked_sub(1).map(|j| bytes[j]);
            let after = bytes.get(i + 2).copied();
            let sep_before = matches!(before, Some(b'-') | Some(b'_'));
            let sep_after = matches!(after, Some(b'-') | Some(b'_') | Some(b'.') | Some(b'/'));
            if sep_before && sep_after {
                return true;
            }
        }
        i += 1;
    }
    false
}

/// Detect a run of exactly `target` repeated placeholder chars (e.g.
/// `NNN`) that is bounded by filename separators. Used to catch
/// `NNN-short-slug.md` while leaving words like "inn" or "running"
/// alone.
fn contains_repeat_run_in_filename_context(token: &str, ch: u8, target: usize) -> bool {
    let bytes = token.as_bytes();
    let mut i = 0;
    while i < bytes.len() {
        if bytes[i] != ch {
            i += 1;
            continue;
        }
        let mut j = i;
        while j < bytes.len() && bytes[j] == ch {
            j += 1;
        }
        let run_len = j - i;
        if run_len == target {
            let before = i.checked_sub(1).map(|k| bytes[k]);
            let after = bytes.get(j).copied();
            let sep_before =
                before.is_none() || matches!(before, Some(b'-') | Some(b'_') | Some(b'/'));
            let sep_after = matches!(
                after,
                Some(b'-') | Some(b'_') | Some(b'.') | Some(b'/') | None
            );
            if sep_before && sep_after {
                return true;
            }
        }
        i = j;
    }
    false
}

/// Reject `/namespace:command` slash-command identifiers (`/codex:review`,
/// `/codex:rescue`). These start with `/` so they trip the absolute-path
/// branch, but the `:` inside the first segment marks them as commands,
/// not filesystem paths.
fn looks_like_slash_command(token: &str) -> bool {
    let Some(rest) = token.strip_prefix('/') else {
        return false;
    };
    let first_segment = match rest.split_once('/') {
        Some((seg, _)) => seg,
        None => rest,
    };
    let Some((ns, cmd)) = first_segment.split_once(':') else {
        return false;
    };
    let valid = |seg: &str| {
        !seg.is_empty()
            && seg
                .chars()
                .all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_')
    };
    valid(ns) && valid(cmd)
}

/// Permissive path-reference detector. Use for tokens the author has
/// marked as a reference — `key_files` entries and backtick-quoted
/// prose tokens. Quoting is an explicit authoring signal; the
/// stem-length and placeholder guards still apply to block obviously
/// malformed references (`.rs`, `YYYY-MM-DD-template.md`).
fn looks_like_surfaced_reference(token: &str) -> bool {
    if token.len() < 2 {
        return false;
    }
    if token.starts_with("http://") || token.starts_with("https://") {
        return false;
    }
    if contains_unresolved_placeholder(token) {
        return false;
    }
    let has_known_extension = ends_with_known_extension(token);
    if has_known_extension && !has_nonempty_stem_before_extension(token) {
        return false;
    }
    if token.contains('/') {
        return has_known_extension || has_anchor_or_repo_prefix(token);
    }
    if has_known_extension {
        return true;
    }
    SURFACED_EXTENSIONLESS_FILENAMES.contains(&token)
}

/// Strict path-reference detector for **unquoted** prose tokens.
///
/// Authors write slashed and extension-bearing phrases in prose
/// (`retire/rename/defend`, `Host/vendor names`, `radar/context_check.rs`,
/// `2026-04-16-my-note.md`) that are not repo path references. Only
/// accept a token as a candidate when the intent is unambiguous:
///
/// - absolute or relative path prefix (`/`, `./`, `../`)
/// - known repo-local prefix (`src/`, `docs/`, `.claude/`, ...)
/// - unslashed bare token from the narrow extensionless filename
///   allowlist (`Dockerfile`, `Makefile`, `LICENSE`, ...)
///
/// Bare extensioned filenames (`backlog.md`, `2026-04-16-my-note.md`)
/// and unprefixed slashed paths (`radar/context_check.rs`,
/// `vendor/cli/README`) are rejected here. Authors who want those
/// validated should quote them in backticks or list them in
/// `key_files`; both paths use the permissive detector.
fn looks_like_unquoted_prose_path(token: &str) -> bool {
    if token.len() < 2 {
        return false;
    }
    if token.starts_with("http://") || token.starts_with("https://") {
        return false;
    }
    if contains_unresolved_placeholder(token) {
        return false;
    }
    if looks_like_slash_command(token) {
        return false;
    }
    if ends_with_known_extension(token) && !has_nonempty_stem_before_extension(token) {
        return false;
    }
    if has_anchor_or_repo_prefix(token) {
        return true;
    }
    if token.contains('/') {
        return false;
    }
    SURFACED_EXTENSIONLESS_FILENAMES.contains(&token)
}

fn strip_sentence_period(text: &str) -> &str {
    let mut chars = text.char_indices().rev();
    let Some((last_idx, last_ch)) = chars.next() else {
        return text;
    };
    if last_ch != '.' {
        return text;
    }
    match chars.next() {
        Some((_, prev))
            if prev.is_alphanumeric() || matches!(prev, '`' | '"' | '\'' | ')' | ']' | '}') =>
        {
            &text[..last_idx]
        }
        _ => text,
    }
}

fn normalize_prose_token(token: &str) -> &str {
    let mut current = token;
    loop {
        let stripped = current
            .trim_matches(|c: char| matches!(c, '`' | '"' | '\'' | ',' | ';' | ':' | '!' | '?'));
        let stripped = strip_sentence_period(stripped);
        if stripped == current {
            return current;
        }
        current = stripped;
    }
}

pub(crate) fn collect_prose_path_candidates(text: &str, out: &mut Vec<String>) {
    // Pass 1: backtick-quoted tokens are an explicit authoring signal.
    // Use the permissive detector so `` `backlog.md` `` and
    // `` `Dockerfile` `` round-trip, even though their unquoted
    // equivalents would be rejected as ambiguous prose.
    let mut cursor = 0usize;
    while let Some(open_rel) = text[cursor..].find('`') {
        let start = cursor + open_rel + 1;
        let Some(close_rel) = text[start..].find('`') else {
            break;
        };
        let end = start + close_rel;
        let quoted = &text[start..end];
        let normalized = normalize_prose_token(quoted);
        if looks_like_surfaced_reference(normalized) {
            out.push(normalized.to_owned());
        }
        cursor = end + 1;
    }

    // Pass 2: unquoted tokens require stronger signals to avoid
    // flagging natural-language slashes, bare extensioned filenames,
    // and Rust module notation.
    for raw in text.split(|c: char| {
        c.is_whitespace() || matches!(c, ',' | ';' | '(' | ')' | '[' | ']' | '{' | '}')
    }) {
        if raw.contains('`') {
            // Token overlaps a backtick pair and has already been
            // considered by Pass 1.
            continue;
        }
        if raw.contains("::") {
            // Rust module notation (`radar/context_check.rs::build_X`)
            // is a code locator, not a filesystem path.
            continue;
        }
        let trimmed = normalize_prose_token(raw);
        if looks_like_unquoted_prose_path(trimmed) {
            out.push(trimmed.to_owned());
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn collect(text: &str) -> Vec<String> {
        let mut out: Vec<String> = Vec::new();
        collect_prose_path_candidates(text, &mut out);
        out
    }

    // Regressions: genuine prose path references should still be collected.
    #[test]
    fn collects_known_root_with_extension() {
        assert_eq!(
            collect("see src/state/consistency.rs"),
            vec!["src/state/consistency.rs"]
        );
    }

    #[test]
    fn collects_docs_path_with_extension() {
        assert_eq!(
            collect("mentioned in docs/dev/2026-04-15-review.md"),
            vec!["docs/dev/2026-04-15-review.md"]
        );
    }

    #[test]
    fn collects_leading_dot_slash_anchor() {
        assert_eq!(
            collect("run ./scripts/build.sh"),
            vec!["./scripts/build.sh"]
        );
    }

    #[test]
    fn collects_bare_known_extensionless_filename() {
        assert_eq!(collect("update the Dockerfile now"), vec!["Dockerfile"]);
    }

    #[test]
    fn collects_backtick_quoted_bare_extensioned_filename() {
        assert_eq!(collect("check `backlog.md` first"), vec!["backlog.md"]);
    }

    #[test]
    fn collects_backtick_quoted_unprefixed_slashed_path() {
        assert_eq!(
            collect("see `radar/context_check.rs` in review"),
            vec!["radar/context_check.rs"]
        );
    }

    // Existing fixes for #526: slash-in-prose and placeholder-date false positives.
    #[test]
    fn skips_slash_separated_identifier_without_extension_or_root() {
        assert!(collect("state, paths, session, start/dispatch, protected_write").is_empty());
    }

    #[test]
    fn skips_natural_language_slash_noun_phrase() {
        assert!(collect("Host/vendor names vary").is_empty());
    }

    #[test]
    fn skips_slash_separated_verb_listing() {
        assert!(collect("retire/rename/defend the surface").is_empty());
    }

    #[test]
    fn skips_slash_separated_identifier_listing() {
        assert!(collect("execution_gates/lease/escalation flow").is_empty());
    }

    #[test]
    fn skips_bare_extensioned_filename_in_prose() {
        assert!(collect("write 2026-04-16-my-note.md later").is_empty());
    }

    #[test]
    fn skips_unresolved_xx_day_placeholder_in_dated_filename() {
        assert!(collect("write docs/dev/2026-04-XX-kernel-review-summary.md later").is_empty());
    }

    #[test]
    fn skips_xxxx_xx_xx_placeholder() {
        assert!(collect("docs/dev/XXXX-XX-XX-template.md placeholder").is_empty());
    }

    #[test]
    fn skips_yyyy_mm_dd_placeholder() {
        assert!(collect("docs/dev/YYYY-MM-DD-template.md").is_empty());
    }

    // #585: new regression guards.
    #[test]
    fn skips_bare_extension_token() {
        assert!(collect("touch .rs files in the tree").is_empty());
        assert!(collect(".md").is_empty());
    }

    #[test]
    fn skips_bare_extension_token_even_when_backticked() {
        assert!(collect("we added `.rs` files").is_empty());
    }

    #[test]
    fn skips_bare_changelog_reference() {
        // Previously emitted because `CHANGELOG` was in the extensionless
        // allowlist; prose almost always means CHANGELOG.md.
        assert!(collect("update the CHANGELOG now").is_empty());
    }

    #[test]
    fn still_collects_backticked_changelog_md() {
        assert_eq!(
            collect("update `CHANGELOG.md` for the release"),
            vec!["CHANGELOG.md"]
        );
    }

    #[test]
    fn skips_nnn_placeholder_in_dated_filename() {
        assert!(collect("write docs/dev/NNN-short-slug.md later").is_empty());
    }

    #[test]
    fn skips_nnn_placeholder_bare() {
        assert!(collect("template NNN-slug.md is a placeholder").is_empty());
    }

    #[test]
    fn does_not_treat_nn_or_nnnn_as_nnn_placeholder() {
        // Two Ns ("CNN") or four Ns should not trigger the NNN guard.
        assert_eq!(
            collect("docs/dev/CNN-report.md exists"),
            vec!["docs/dev/CNN-report.md"]
        );
    }

    #[test]
    fn skips_rust_module_notation() {
        assert!(
            collect("trace radar/context_check.rs::build_context_check_decision for detail")
                .is_empty()
        );
    }

    #[test]
    fn skips_unprefixed_slashed_rust_path_in_unquoted_prose() {
        // Per issue #585: `radar/context_check.rs` mentioned bare in
        // prose should not be treated as a repo path (real file lives
        // at src/state/radar/context_check.rs). Authors who want the
        // bare path validated can backtick it.
        assert!(collect("see radar/context_check.rs for detail").is_empty());
    }

    #[test]
    fn skips_slash_command_identifier() {
        assert!(collect("run /codex:review before merging").is_empty());
        assert!(collect("run /codex:rescue if blocked").is_empty());
    }

    #[test]
    fn does_not_confuse_slash_command_with_absolute_path() {
        // A real absolute path (no `:` in first segment) must still be
        // treated as a path candidate.
        assert_eq!(
            collect("ship /usr/local/bin/ccd with the package"),
            vec!["/usr/local/bin/ccd"]
        );
    }
}

pub(crate) fn extract_key_files_candidates(text: &str) -> Vec<String> {
    let trimmed = text.trim();
    let mut candidates: Vec<String> = Vec::new();

    if let Some(rest) = trimmed.strip_prefix('`') {
        if let Some(end) = rest.find('`') {
            let path = &rest[..end];
            if !path.is_empty() {
                candidates.push(path.to_owned());
                return candidates;
            }
        }
    }

    let stripped = trimmed.trim_matches(|c: char| matches!(c, '`' | '"' | '\''));
    if !stripped.is_empty() {
        candidates.push(stripped.to_owned());
    }

    if let Some((prefix, _)) = stripped.split_once(" - ") {
        let prefix = prefix.trim();
        if !prefix.is_empty() && prefix != stripped {
            candidates.push(prefix.to_owned());
        }
    }

    candidates
}