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
// Agent file claims (MACS F4 / ULTRA-002) — an enforced ownership invariant
// for multi-agent workflows.
//
// Measured problem: every ultracode prompt had to hand-partition file ownership
// across 6-11 concurrent agents. When the partition was wrong, work was lost —
// in one round FIVE findings returned "blocked-by-file-claim" having done
// nothing, because two agents needed the same file and neither could tell.
//
// This turns that prompt convention into an invariant the ledger enforces:
// `acquire` refuses on conflict (non-zero exit), `release` gives the paths
// back, and a crashed agent's claim expires by TTL instead of blocking the
// pool forever. Expiry is REPRESENTABLE, never silent: an expired claim is
// reported as expired and a supersession is recorded on the journal.
//
// Storage: `.pmat-work/claims.jsonl`, append-only, one JSON record per line —
// the same shape as `ledger.jsonl` and `events.jsonl`. State is a fold over
// the journal in file order; file order is also the tie-break that resolves a
// race between two agents appending at the same instant.
/// Default claim lifetime. A crashed agent must not hold a path forever, and
/// "no expiry" would make that the default outcome.
pub const DEFAULT_CLAIM_TTL_SECS: u64 = 3600;
/// Upper bound on a single appended line. POSIX guarantees an `O_APPEND` write
/// below `PIPE_BUF` (4096) is atomic; above it two concurrent agents can
/// interleave and corrupt the journal, so an over-large claim is refused
/// rather than silently risked.
const MAX_CLAIM_LINE_BYTES: usize = 4000;
/// What a journal line does to the claim state.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum FileClaimAction {
/// Take ownership of the listed paths
Acquire,
/// Give the listed paths back
Release,
}
/// One line in `.pmat-work/claims.jsonl`.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct FileClaimRecord {
/// Record id, e.g. "cl-0197f0..."
pub id: String,
/// ISO 8601 timestamp the record was written
pub recorded_at: String,
/// Acquire or release
pub action: FileClaimAction,
/// Agent identity (free-form; the workflow's name for the subagent)
pub agent: String,
/// Normalized, repo-relative paths
pub paths: Vec<String>,
/// When an acquire stops holding (RFC 3339). Absent on releases.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub expires_at: Option<String>,
/// Ticket this claim belongs to, if any
#[serde(default, skip_serializing_if = "Option::is_none")]
pub work_item_id: Option<String>,
/// Operator note
#[serde(default, skip_serializing_if = "Option::is_none")]
pub note: Option<String>,
/// Reason a claim was taken from / released out from under another agent
#[serde(default, skip_serializing_if = "Option::is_none")]
pub forced_reason: Option<String>,
/// Agents whose expired claims this acquire superseded. Recorded so an
/// expiry is auditable rather than a silent handover.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub superseded_expired: Vec<String>,
}
/// A path currently owned by an agent, as folded from the journal.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ActiveFileClaim {
/// Journal record that granted it
pub record_id: String,
/// Owning agent
pub agent: String,
/// Normalized repo-relative path
pub path: String,
/// When it was taken
pub acquired_at: String,
/// When it lapses (RFC 3339)
pub expires_at: String,
/// Ticket, if declared
pub work_item_id: Option<String>,
/// Line index in the journal — the total order that settles a race
pub seq: usize,
/// True once `now` is past `expires_at`
pub expired: bool,
}
/// Normalize one claim path to a repo-relative, slash-joined form.
///
/// Refuses rather than guesses: `..` is ambiguous under a shared root, globs
/// are not what prefix-claims mean, and an absolute path outside the project
/// cannot be claimed in this project's journal.
pub fn normalize_claim_path(raw: &str, project_root: &Path) -> Result<String> {
let trimmed = raw.trim();
if trimmed.is_empty() {
anyhow::bail!("claim path is empty");
}
if trimmed.contains('*') || trimmed.contains('?') {
anyhow::bail!(
"claim path '{trimmed}' contains a glob; claim the directory instead \
(a directory claim covers everything beneath it)"
);
}
let relative = strip_project_root(trimmed, project_root)?;
join_normalized_components(&relative, trimmed)
}
/// Make an absolute path repo-relative, or refuse if it is outside the project.
fn strip_project_root(trimmed: &str, project_root: &Path) -> Result<String> {
let candidate = Path::new(trimmed);
if !candidate.is_absolute() {
return Ok(trimmed.to_string());
}
let root = project_root
.canonicalize()
.unwrap_or_else(|_| project_root.to_path_buf());
match candidate.strip_prefix(&root) {
Ok(rel) => Ok(rel.to_string_lossy().to_string()),
Err(_) => anyhow::bail!(
"claim path '{trimmed}' is outside the project root {}; \
claims are recorded repo-relative",
root.display()
),
}
}
/// Drop `.` components, refuse `..`, and reject a path that normalizes to
/// nothing (which would silently claim the whole repository).
fn join_normalized_components(relative: &str, original: &str) -> Result<String> {
let mut parts: Vec<&str> = Vec::new();
for component in relative.split('/') {
match component {
"" | "." => continue,
".." => anyhow::bail!(
"claim path '{original}' contains '..'; pass a path relative to \
the project root"
),
other => parts.push(other),
}
}
if parts.is_empty() {
anyhow::bail!("claim path '{original}' normalizes to the project root; refusing");
}
Ok(parts.join("/"))
}
/// True when two normalized claims cover any common file: equal, or one is a
/// directory prefix of the other. `src/cli` does not overlap `src/cli_x`.
pub fn claim_paths_overlap(a: &str, b: &str) -> bool {
a == b || is_dir_prefix(a, b) || is_dir_prefix(b, a)
}
fn is_dir_prefix(dir: &str, child: &str) -> bool {
child.len() > dir.len() && child.starts_with(dir) && child.as_bytes()[dir.len()] == b'/'
}
/// Append-only claim journal over `.pmat-work/claims.jsonl`.
pub struct FileClaimLedger {
work_dir: PathBuf,
}
impl FileClaimLedger {
/// Open the journal for a project (the file need not exist yet).
pub fn new(project_path: &Path) -> Self {
Self {
work_dir: project_path.join(".pmat-work"),
}
}
/// Path to `claims.jsonl`.
pub fn journal_path(&self) -> PathBuf {
self.work_dir.join("claims.jsonl")
}
/// Every record in file order. A malformed line is an error, not a skip:
/// a claim journal that quietly drops lines under-reports conflicts, which
/// is the failure this command exists to prevent.
pub fn load_records(&self) -> Result<Vec<FileClaimRecord>> {
let path = self.journal_path();
if !path.exists() {
return Ok(Vec::new());
}
let text = std::fs::read_to_string(&path).context("Failed to read claims.jsonl")?;
let mut records = Vec::new();
for (idx, line) in text.lines().enumerate() {
let line = line.trim();
if line.is_empty() {
continue;
}
records.push(
serde_json::from_str::<FileClaimRecord>(line).with_context(|| {
format!("claims.jsonl line {} is not a claim record", idx + 1)
})?,
);
}
Ok(records)
}
/// Append one record. Refuses a line long enough to lose `O_APPEND`
/// atomicity, because a torn line corrupts every later verdict.
pub fn append(&self, record: &FileClaimRecord) -> Result<()> {
use std::io::Write;
std::fs::create_dir_all(&self.work_dir).context("Failed to create .pmat-work directory")?;
let mut line = serde_json::to_string(record).context("Failed to serialize claim record")?;
if line.len() > MAX_CLAIM_LINE_BYTES {
anyhow::bail!(
"claim record is {} bytes, over the {MAX_CLAIM_LINE_BYTES}-byte atomic-append \
limit; split it into several `pmat work claim acquire` calls",
line.len()
);
}
line.push('\n');
let mut file = std::fs::OpenOptions::new()
.create(true)
.append(true)
.open(self.journal_path())
.context("Failed to open claims.jsonl")?;
file.write_all(line.as_bytes())
.context("Failed to append claim record")?;
Ok(())
}
/// Fold the journal into the set of paths currently owned, evaluated at
/// `now`. Expired claims are retained and flagged, not dropped.
pub fn active_claims(
&self,
now: chrono::DateTime<chrono::Utc>,
) -> Result<Vec<ActiveFileClaim>> {
Ok(fold_claims(&self.load_records()?, now))
}
}
/// Pure fold used by [`FileClaimLedger::active_claims`]; `now` is injected so
/// expiry is testable without sleeping.
pub fn fold_claims(
records: &[FileClaimRecord],
now: chrono::DateTime<chrono::Utc>,
) -> Vec<ActiveFileClaim> {
let mut active: Vec<ActiveFileClaim> = Vec::new();
for (seq, record) in records.iter().enumerate() {
match record.action {
FileClaimAction::Acquire => apply_acquire(&mut active, record, seq, now),
FileClaimAction::Release => apply_release(&mut active, record),
}
}
for claim in &mut active {
claim.expired = is_expired(&claim.expires_at, now);
}
active
}
/// An acquire takes a path only if nothing live and foreign already covers it.
/// The agent's own overlapping claim is replaced (a refresh), and a live
/// foreign claim makes this acquire a no-op — that is how the loser of an
/// append race is decided, deterministically, by file order.
fn apply_acquire(
active: &mut Vec<ActiveFileClaim>,
record: &FileClaimRecord,
seq: usize,
now: chrono::DateTime<chrono::Utc>,
) {
let expires_at = record.expires_at.clone().unwrap_or_default();
for path in &record.paths {
let blocked = active.iter().any(|c| {
c.agent != record.agent
&& claim_paths_overlap(&c.path, path)
&& !is_expired(&c.expires_at, now)
});
if blocked && record.forced_reason.is_none() {
continue;
}
// Drop what this acquire replaces: the agent's own overlapping claim
// (a refresh), a lapsed claim it supersedes, and — under --force —
// whatever it took. Leaving a superseded lapsed row behind would list
// one path as owned twice.
active.retain(|c| {
!(claim_paths_overlap(&c.path, path)
&& (c.agent == record.agent
|| record.forced_reason.is_some()
|| is_expired(&c.expires_at, now)))
});
active.push(ActiveFileClaim {
record_id: record.id.clone(),
agent: record.agent.clone(),
path: path.clone(),
acquired_at: record.recorded_at.clone(),
expires_at: expires_at.clone(),
work_item_id: record.work_item_id.clone(),
seq,
expired: false,
});
}
}
/// A release drops the agent's own exact paths; `--force` releases another
/// agent's, and carries the reason on the record.
fn apply_release(active: &mut Vec<ActiveFileClaim>, record: &FileClaimRecord) {
let forced = record.forced_reason.is_some();
active.retain(|c| {
!(record.paths.iter().any(|p| p == &c.path) && (forced || c.agent == record.agent))
});
}
/// True when `now` is at or past an RFC 3339 expiry. An unparseable or empty
/// expiry counts as expired: a claim whose lifetime cannot be read must not
/// block the pool forever.
pub fn is_expired(expires_at: &str, now: chrono::DateTime<chrono::Utc>) -> bool {
match chrono::DateTime::parse_from_rfc3339(expires_at) {
Ok(t) => now >= t.with_timezone(&chrono::Utc),
Err(_) => true,
}
}
/// Build an acquire record (id and timestamps filled in here).
pub fn new_acquire_record(
agent: &str,
paths: Vec<String>,
ttl_secs: u64,
now: chrono::DateTime<chrono::Utc>,
) -> FileClaimRecord {
FileClaimRecord {
id: format!("cl-{}", Uuid::now_v7().simple()),
recorded_at: now.to_rfc3339(),
action: FileClaimAction::Acquire,
agent: agent.to_string(),
paths,
expires_at: Some((now + chrono::Duration::seconds(ttl_secs as i64)).to_rfc3339()),
work_item_id: None,
note: None,
forced_reason: None,
superseded_expired: Vec::new(),
}
}
/// Build a release record.
pub fn new_release_record(
agent: &str,
paths: Vec<String>,
now: chrono::DateTime<chrono::Utc>,
) -> FileClaimRecord {
FileClaimRecord {
id: format!("cl-{}", Uuid::now_v7().simple()),
recorded_at: now.to_rfc3339(),
action: FileClaimAction::Release,
agent: agent.to_string(),
paths,
expires_at: None,
work_item_id: None,
note: None,
forced_reason: None,
superseded_expired: Vec::new(),
}
}