Skip to content

Commit d860a13

Browse files
committed
fix: align patch context and fmt CLI contracts
Refs #40
1 parent 54166a2 commit d860a13

13 files changed

Lines changed: 301 additions & 97 deletions

‎CHANGELOG.md‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -65,6 +65,11 @@ format: `Unreleased` then release buckets, grouped by impact.
6565
scratch locals follow function parameters instead of aliasing parameters or
6666
user `let` bindings. Parameterized narrow-integer programs now validate and
6767
agree with the reference interpreter.
68+
- The CLI now rejects single-file semantic-patch no-ops and read-only sources
69+
before staging, admits Context byte budgets only from the viable 2048-byte
70+
envelope floor, and refuses `fmt` source, manifest, or project-directory
71+
symlink/reparse aliases with `SPX-J102`.
72+
6873
- Cleanup replay now validates long scalar checked-status sequences through
6974
bounded status-source/edge/exit summaries instead of cloning every failed
7075
path's successful prefix, eliminating quadratic replay memory and preflight

‎docs/AGENT-CONTEXT-V2.md‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,11 @@ semaprax context <file> <symbol|stable-id>
1313
[--filters contracts,ownership,effects,types,targets,diagnostics,tests]
1414
```
1515

16+
The admitted byte budget is `2048..=16777216`. The lower bound is large
17+
enough for the smallest canonical v1/v2 envelope; longer identities or a
18+
resumable frontier can still require the exact larger budget reported by
19+
`SPX-G004` or by a frontier cursor.
20+
1621
The public Rust surface is `AgentContextDirection`,
1722
`AgentContextV2Options`, and `agent_context_v2_json`. Direction names are
1823
closed, exact, and case-sensitive. Unknown, missing, or duplicated direction

‎docs/CLI-GUIDE.md‎

Lines changed: 8 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -74,12 +74,14 @@ directly runnable.
7474

7575
`fmt <file> --check` reports non-canonical source without rewriting it. Run
7676
`fmt <file>` without `--check` when you want the compiler to rewrite that file
77-
canonically. `fmt` also takes a project directory or `semaprax.toml`: `fmt .
78-
--check` names every drifting source and its first differing line, in manifest
79-
order, and `fmt .` rewrites them, parsing every file before writing any.
80-
Canonical expression formatting is compact: a `match` remains on one line even
81-
when its source arms span several lines. `//` comments survive formatting:
82-
each is printed on its own line above the
77+
canonically. Write-capable formatting rejects symlink/reparse aliases for a
78+
source, manifest, or project directory as `SPX-J102`, consistently with
79+
Project input selection. `fmt` also takes a project directory or
80+
`semaprax.toml`: `fmt . --check` names every drifting source and its first
81+
differing line, in manifest order, and `fmt .` rewrites them, parsing every
82+
file before writing any. Canonical expression formatting is compact: a
83+
`match` remains on one line even when its source arms span several lines. `//`
84+
comments survive formatting: each is printed on its own line above the
8385
declaration, field, or statement it precedes, or right after the one it
8486
followed; [canonical comments](CANONICAL-COMMENTS-V1.md) owns the exact
8587
placement rules and lists the routes that preserve comments.

‎docs/PROJECT-MANIFEST-V1.md‎

Lines changed: 8 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -113,12 +113,14 @@ manifest. For `check`, `run`, `test`, `build`, and `fmt`, a positional operand
113113
that names an existing directory selects the `semaprax.toml` inside it, with
114114
inert `.` components removed; `--manifest-path` is never resolved this way, and
115115
a directory without a manifest reports `SPX-J102` for that path. `fmt <dir>`
116-
and `fmt semaprax.toml` read only the manifest, not the authenticated project:
117-
they format every `sources` entry in manifest order through the single-file
118-
comment-preserving projection, parse every file before writing any, and with
119-
`--check` print one `<path>:<line> is not canonically formatted` line per
120-
drifting file, naming its first differing line, and exit one; a manifest that
121-
cannot be read is reported as `cannot read
116+
and `fmt semaprax.toml` do not load the authenticated semantic project, but
117+
they reject a symlink/reparse point in the selected directory, manifest, or
118+
source ancestry before writing. They format every `sources` entry in manifest
119+
order through the single-file comment-preserving projection, parse every file
120+
before writing any, and with `--check` print one
121+
`<path>:<line> is not canonically formatted` line per drifting file, naming
122+
its first differing line, and exit one; a manifest that cannot be read is
123+
reported as `cannot read
122124
<path>`. Project builds publish two explicit targets:
123125

124126
- `--target web` (the default) publishes the digest-bound scalar Web package;

‎docs/SEMANTIC-PATCH-V2.md‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -65,6 +65,12 @@ lower-schema programs remain v10-v13, and CleanupPlan selection is unchanged.
6565
- Existing v1 parse, name, stale-revision, effect, verification, and A0 I/O
6666
diagnostics retain their codes and behavior.
6767

68+
The direct single-file apply route also rejects a schema-less rename whose
69+
candidate revision equals its base as `SPX-G106`, before creating a staging
70+
file. A source whose retained permissions are read-only rejects as
71+
`SPX-I205`; atomic replacement never turns read-only input into write
72+
authority.
73+
6874
## Threat model and nonclaims
6975

7076
The source snapshot, lock, staging handle, sibling paths, final source reparse,

‎src/cli/fmt.rs‎

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -68,6 +68,7 @@ pub(crate) fn run(options: FmtOptions, report: impl Fn(&[Diagnostic]) -> u8) ->
6868
};
6969
let mut formatted = Vec::with_capacity(paths.len());
7070
for path in paths {
71+
reject_symlink_components(&path).map_err(|diagnostic| report(&[diagnostic]))?;
7172
let source = std::fs::read_to_string(&path).map_err(|error| {
7273
report(&[Diagnostic::io(
7374
"SPX-I001",
@@ -130,6 +131,7 @@ fn project_sources(
130131
manifest_path: &Path,
131132
report: &impl Fn(&[Diagnostic]) -> u8,
132133
) -> Result<Vec<PathBuf>, u8> {
134+
reject_symlink_components(manifest_path).map_err(|diagnostic| report(&[diagnostic]))?;
133135
let manifest_source = std::fs::read_to_string(manifest_path).map_err(|error| {
134136
report(&[Diagnostic::io(
135137
"SPX-J102",
@@ -150,6 +152,51 @@ fn project_sources(
150152
.collect())
151153
}
152154

155+
/// Formatting is a write-capable Project command, so it rejects the same
156+
/// symlink/reparse aliases as authenticated Project selection. Missing paths
157+
/// are left to the existing read diagnostic.
158+
fn reject_symlink_components(path: &Path) -> Result<(), Diagnostic> {
159+
let absolute = if path.is_absolute() {
160+
path.to_path_buf()
161+
} else {
162+
std::env::current_dir()
163+
.map_err(|error| {
164+
Diagnostic::io(
165+
"SPX-J102",
166+
format!("cannot inspect fmt input {}: {error}", path.display()),
167+
)
168+
})?
169+
.join(path)
170+
};
171+
for component in absolute.ancestors() {
172+
let Ok(metadata) = std::fs::symlink_metadata(component) else {
173+
continue;
174+
};
175+
if metadata.file_type().is_symlink() || metadata_is_reparse(&metadata) {
176+
return Err(Diagnostic::io(
177+
"SPX-J102",
178+
format!(
179+
"fmt input {} traverses a symlink or reparse point at {}",
180+
path.display(),
181+
component.display()
182+
),
183+
));
184+
}
185+
}
186+
Ok(())
187+
}
188+
189+
#[cfg(windows)]
190+
fn metadata_is_reparse(metadata: &std::fs::Metadata) -> bool {
191+
use std::os::windows::fs::MetadataExt;
192+
metadata.file_attributes() & 0x400 != 0
193+
}
194+
195+
#[cfg(not(windows))]
196+
fn metadata_is_reparse(_: &std::fs::Metadata) -> bool {
197+
false
198+
}
199+
153200
#[cfg(test)]
154201
mod tests {
155202
use super::*;

‎src/graph.rs‎

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -103,9 +103,10 @@ pub fn context_json(
103103
pub const MAX_AGENT_CONTEXT_BYTES: usize = 16 * 1024 * 1024;
104104
/// Smallest accepted requested byte budget.
105105
///
106-
/// A particular query can still fail closed when its canonical envelope and
107-
/// first resumable frontier entry do not fit this budget.
108-
pub const MIN_AGENT_CONTEXT_BYTES: usize = 1024;
106+
/// This leaves room for the smallest canonical Context v1/v2 envelope. A
107+
/// particular query can still fail closed when its identity fields or first
108+
/// resumable frontier entry do not fit this budget.
109+
pub const MIN_AGENT_CONTEXT_BYTES: usize = 2048;
109110
/// Maximum function-fact budget accepted by one query.
110111
pub const MAX_AGENT_CONTEXT_NODES: usize = 65_536;
111112
/// Maximum transitive call depth accepted by one context query.

‎src/patch.rs‎

Lines changed: 2 additions & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
mod direct_apply;
12
mod source_index;
23

34
use std::collections::{BTreeMap, BTreeSet};
@@ -10,6 +11,7 @@ use crate::ast::{Program, Type, TypeDeclaration, TypeDeclarationKind};
1011
use crate::diagnostic::Diagnostic;
1112
use crate::{graph, hir, lexer, parse, verify};
1213

14+
use self::direct_apply::apply_with_commit_hook;
1315
use self::source_index::SemanticSourceIndex;
1416

1517
#[derive(Debug)]
@@ -1995,39 +1997,6 @@ fn preflight_parsed_owned(
19951997
})
19961998
}
19971999

1998-
fn apply_with_commit_hook(
1999-
source_path: &Path,
2000-
patch_path: &Path,
2001-
hook: impl FnMut(CommitPhase, &Path, &Path) -> std::io::Result<()>,
2002-
) -> Result<String, Vec<Diagnostic>> {
2003-
let guard = acquire_a0_commit_guard(source_path)?;
2004-
let patch_source = std::fs::read_to_string(patch_path).map_err(|error| {
2005-
vec![Diagnostic::io(
2006-
"SPX-I202",
2007-
format!("cannot read {}: {error}", patch_path.display()),
2008-
)]
2009-
})?;
2010-
let parsed_patch = parse_patch(&patch_source)?;
2011-
let bounded_v3 = parsed_patch.schema == PatchSchema::V3;
2012-
let authenticated = if bounded_v3 {
2013-
authenticate_a0_source(&guard, Some((crate::repair::MAX_SOURCE_BYTES, "SPX-R101")))?
2014-
} else {
2015-
authenticate_a0_source(&guard, None)?
2016-
};
2017-
let source = authenticated.source().to_owned();
2018-
let preflight = preflight_parsed_owned(
2019-
source,
2020-
patch_source,
2021-
source_path.to_path_buf(),
2022-
parsed_patch,
2023-
None,
2024-
None,
2025-
CandidateValidation::Standalone,
2026-
)?;
2027-
let prepared = prepare_a0_commit(&authenticated, &preflight)?;
2028-
commit_prepared_a0(prepared, hook)
2029-
}
2030-
20312000
pub(crate) fn commit_prepared_a0(
20322001
prepared: A0PreparedCommit<'_>,
20332002
hook: impl FnMut(CommitPhase, &Path, &Path) -> std::io::Result<()>,

‎src/patch/direct_apply.rs‎

Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
//! Direct single-file Patch admission before the shared A0 commit core.
2+
3+
use super::*;
4+
5+
pub(super) fn apply_with_commit_hook(
6+
source_path: &Path,
7+
patch_path: &Path,
8+
hook: impl FnMut(CommitPhase, &Path, &Path) -> std::io::Result<()>,
9+
) -> Result<String, Vec<Diagnostic>> {
10+
let guard = acquire_a0_commit_guard(source_path)?;
11+
let patch_source = std::fs::read_to_string(patch_path).map_err(|error| {
12+
vec![Diagnostic::io(
13+
"SPX-I202",
14+
format!("cannot read {}: {error}", patch_path.display()),
15+
)]
16+
})?;
17+
let parsed_patch = parse_patch(&patch_source)?;
18+
let bounded_v3 = parsed_patch.schema == PatchSchema::V3;
19+
let authenticated = if bounded_v3 {
20+
authenticate_a0_source(&guard, Some((crate::repair::MAX_SOURCE_BYTES, "SPX-R101")))?
21+
} else {
22+
authenticate_a0_source(&guard, None)?
23+
};
24+
reject_read_only_source(&authenticated.snapshot, source_path)?;
25+
let source = authenticated.source().to_owned();
26+
let preflight = preflight_parsed_owned(
27+
source,
28+
patch_source,
29+
source_path.to_path_buf(),
30+
parsed_patch,
31+
None,
32+
None,
33+
CandidateValidation::Standalone,
34+
)?;
35+
if preflight.base_revision() == preflight.candidate_revision() {
36+
return Err(patch_conflict(
37+
"semantic patch produces no semantic revision change",
38+
));
39+
}
40+
let prepared = prepare_a0_commit(&authenticated, &preflight)?;
41+
commit_prepared_a0(prepared, hook)
42+
}
43+
44+
fn reject_read_only_source(
45+
snapshot: &SourceSnapshot,
46+
diagnostic_path: &Path,
47+
) -> Result<(), Vec<Diagnostic>> {
48+
if snapshot.permissions.readonly() {
49+
return Err(vec![Diagnostic::io(
50+
"SPX-I205",
51+
format!(
52+
"semantic patch source {} is read-only",
53+
diagnostic_path.display()
54+
),
55+
)]);
56+
}
57+
Ok(())
58+
}

0 commit comments

Comments
 (0)