Class: Agent::Lock::Record

Inherits:
Object
  • Object
show all
Defined in:
lib/agent/lock/record.rb

Overview

One lock, on disk.

A markdown file with YAML front matter, rather than plain YAML, because the interesting half of a lock is the sentence saying what the holder is doing. An agent that finds a file locked can read that and decide whether to wait or to work elsewhere; "occupied" tells it nothing. A human opening the file in an editor sees the same thing.

---
agent_id: claude-9feca100
scope: workflow/**
pid: 69232
---
Rewriting the installer's filter pair.

Constant Summary collapse

FIELDS =

The front-matter keys, in the order they are written. Each one is also a reader on the record.

%i[id agent_id parent_agent_id scope tree repo branch worktree pid started started_at host
created_at updated_at status frozen_paths].freeze
ACTIVE =

The status of a live claim.

"active"
ORPHANED =

The status of a lock whose holder died with notes in it: it blocks nobody, but is kept until somebody resumes or breaks it.

"orphaned"
SEPARATOR =

What fences the YAML front matter off from the body.

"---"
NOTES_HEADING =

The heading note appends under.

"## Progress"
NOTES_SECTION =

What note leaves in the body: the heading on a line of its own and, straight under it, an entry that opens with the time it was written. Finding this, not the heading's words, is what makes a dead holder's lock worth orphaning rather than deleting: an intent that mentioned ## Progress used to pass for notes, and the lock of a holder that wrote none was kept as interrupted work until somebody broke it.

/^#{Regexp.escape(NOTES_HEADING)}\n- \d{4}-\d\d-\d\dT\d\d:\d\d:\d\dZ(?: |$)/
HEADING_LINE =

A line of an intent that is the heading and nothing else, give or take the whitespace around it. Matches the empty spot in front of the ##, which is where escape_heading puts its backslash.

/^[ \t]*\K(?=#{Regexp.escape(NOTES_HEADING)}[ \t\r]*$)/

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(intent: "", path: nil, **fields) ⇒ Record

Returns a new instance of Record.

Parameters:

  • intent (String) (defaults to: "") —

    the body: what the holder is doing, plus its notes

  • path (String, nil) (defaults to: nil) —

    the file it was read from, for the file store

  • fields (Hash{Symbol => Object}) —

    any of FIELDS



172
173
174
175
176
177
# File 'lib/agent/lock/record.rb', line 172

def initialize(intent: "", path: nil, **fields)
  FIELDS.each { |field| instance_variable_set(:"@#{field}", fields[field]) }
  @frozen_paths = Array(@frozen_paths)
  @intent = intent.to_s
  @path = path
end

Instance Attribute Details

#agent_id ⇒ String (readonly)

Returns who holds it, see Identity#id.

Returns:



95
# File 'lib/agent/lock/record.rb', line 95

FIELDS.each { |field| attr_reader(field) }

#branch ⇒ String? (readonly)

Returns the branch it was taken on; nil on a detached HEAD.

Returns:

  • (String, nil) —

    the branch it was taken on; nil on a detached HEAD



95
# File 'lib/agent/lock/record.rb', line 95

FIELDS.each { |field| attr_reader(field) }

#created_at ⇒ String (readonly)

Returns ISO 8601, UTC.

Returns:

  • (String) —

    ISO 8601, UTC



95
# File 'lib/agent/lock/record.rb', line 95

FIELDS.each { |field| attr_reader(field) }

#frozen_paths ⇒ Array<String> (readonly)

Returns files --enforce froze, so a release can thaw them.

Returns:

  • (Array<String>) —

    files --enforce froze, so a release can thaw them



95
# File 'lib/agent/lock/record.rb', line 95

FIELDS.each { |field| attr_reader(field) }

#host ⇒ String? (readonly)

Returns the machine the holder runs on.

Returns:

  • (String, nil) —

    the machine the holder runs on



95
# File 'lib/agent/lock/record.rb', line 95

FIELDS.each { |field| attr_reader(field) }

#id ⇒ String (readonly)

Returns <scope slug>-<digest>, the same on every clone of a branch.

Returns:

  • (String) —

    <scope slug>-<digest>, the same on every clone of a branch



95
# File 'lib/agent/lock/record.rb', line 95

FIELDS.each { |field| attr_reader(field) }

#intent ⇒ String (readonly)

Returns the body: what the holder is doing, then its notes.

Returns:

  • (String) —

    the body: what the holder is doing, then its notes



98
99
100
# File 'lib/agent/lock/record.rb', line 98

def intent
  @intent
end

#parent_agent_id ⇒ String? (readonly)

Returns the session that spawned the holder, if any.

Returns:

  • (String, nil) —

    the session that spawned the holder, if any



95
# File 'lib/agent/lock/record.rb', line 95

FIELDS.each { |field| attr_reader(field) }

#path ⇒ String? (readonly)

Returns the file it was read from; nil outside the file store.

Returns:

  • (String, nil) —

    the file it was read from; nil outside the file store



101
102
103
# File 'lib/agent/lock/record.rb', line 101

def path
  @path
end

#pid ⇒ Integer? (readonly)

Returns the holder's session process, used to reap it.

Returns:

  • (Integer, nil) —

    the holder's session process, used to reap it



95
# File 'lib/agent/lock/record.rb', line 95

FIELDS.each { |field| attr_reader(field) }

#repo ⇒ String? (readonly)

Returns the repository it was taken in, see Tree#repo.

Returns:

  • (String, nil) —

    the repository it was taken in, see Tree#repo



95
# File 'lib/agent/lock/record.rb', line 95

FIELDS.each { |field| attr_reader(field) }

#scope ⇒ String (readonly)

Returns the normalized glob, relative to the tree root.

Returns:

  • (String) —

    the normalized glob, relative to the tree root



95
# File 'lib/agent/lock/record.rb', line 95

FIELDS.each { |field| attr_reader(field) }

#started ⇒ String? (readonly)

Returns where a 4.0.0 gem kept that process's start time, as ps printed it in the holder's own time zone and locale. Read, and no longer written: a 4.0.0 gem reading a lock without it goes by the pid alone, and so never reaps a live holder.

Returns:

  • (String, nil) —

    where a 4.0.0 gem kept that process's start time, as ps printed it in the holder's own time zone and locale. Read, and no longer written: a 4.0.0 gem reading a lock without it goes by the pid alone, and so never reaps a live holder



95
# File 'lib/agent/lock/record.rb', line 95

FIELDS.each { |field| attr_reader(field) }

#started_at ⇒ String? (readonly)

Returns that process's start time, ISO 8601 and UTC, so a recycled pid is not mistaken for it.

Returns:

  • (String, nil) —

    that process's start time, ISO 8601 and UTC, so a recycled pid is not mistaken for it



95
# File 'lib/agent/lock/record.rb', line 95

FIELDS.each { |field| attr_reader(field) }

#status ⇒ String (readonly)

Returns ACTIVE or ORPHANED.

Returns:



95
# File 'lib/agent/lock/record.rb', line 95

FIELDS.each { |field| attr_reader(field) }

#tree ⇒ String (readonly)

Returns the absolute root of the checkout that took it.

Returns:

  • (String) —

    the absolute root of the checkout that took it



95
# File 'lib/agent/lock/record.rb', line 95

FIELDS.each { |field| attr_reader(field) }

#updated_at ⇒ String? (readonly)

Returns ISO 8601, UTC, the last note or resume.

Returns:

  • (String, nil) —

    ISO 8601, UTC, the last note or resume



95
# File 'lib/agent/lock/record.rb', line 95

FIELDS.each { |field| attr_reader(field) }

#worktree ⇒ Boolean (readonly)

Returns whether the checkout was a linked worktree.

Returns:

  • (Boolean) —

    whether the checkout was a linked worktree



95
# File 'lib/agent/lock/record.rb', line 95

FIELDS.each { |field| attr_reader(field) }

Class Method Details

.build(scope:, tree:, identity:, intent:) ⇒ Record

Parameters:

Returns:



109
110
111
112
113
114
115
116
117
# File 'lib/agent/lock/record.rb', line 109

def build(scope:, tree:, identity:, intent:)
  evidence = identity.evidence
  new(
    id: id_for(tree, scope), agent_id: identity.id, parent_agent_id: identity.parent_id,
    scope: scope.to_s, tree: tree.root, repo: tree.repo, branch: tree.branch, worktree: tree.worktree?,
    pid: evidence[:pid], started_at: evidence[:started_at], host: evidence[:host],
    created_at: Time.now.utc.iso8601, status: ACTIVE, frozen_paths: [], intent: escape_heading(intent)
  )
end

.escape_heading(intent) ⇒ String

An intent that cannot pass for notes. The body is one markdown text, the intent and then the notes, so an intent that pasted a notes section (the output of alock show, say) read as notes nobody wrote. A line that is the heading gets markdown's own escape, \## Progress: the words stay readable and stop being a heading, here and in a renderer.

Stripped first because every store strips the body, which would otherwise uncover a heading behind leading whitespace only after this had looked.

Parameters:

  • intent (String, nil) —

    as the caller gave it

Returns:

  • (String)


132
# File 'lib/agent/lock/record.rb', line 132

def escape_heading(intent) = intent.to_s.strip.gsub(HEADING_LINE) { "\\" }

.id_for(tree, scope) ⇒ String

Derived from the tree's lock key and the scope so that a second run looking for the same lock finds it without reading every file in the store, and so that two checkouts of one branch, on any machine, are after the same id and cannot both win it.

Parameters:

Returns:

  • (String)


142
143
144
145
# File 'lib/agent/lock/record.rb', line 142

def id_for(tree, scope)
  digest = Digest::SHA256.hexdigest("#{tree.lock_key}\0#{scope}")[0, 8]
  "#{scope.slug}-#{digest}"
end

.parse(text, path: nil) ⇒ Record?

Parameters:

  • text (String) —

    a lock document, from a file or from Redis

  • path (String, nil) (defaults to: nil) —

    the file it was read from, for the file store

Returns:



158
159
160
161
162
163
164
165
166
# File 'lib/agent/lock/record.rb', line 158

def parse(text, path: nil)
  _, front, body = text.to_s.split(/^#{SEPARATOR}\s*$/, 3)
  data = YAML.safe_load(front.to_s, permitted_classes: [], aliases: false)
  return nil unless data.is_a?(Hash)

  new(**data.transform_keys(&:to_sym).slice(*FIELDS), intent: body.to_s.strip, path: path)
rescue Psych::Exception, ArgumentError
  nil
end

.read(path) ⇒ Record?

Returns nil for a file this gem did not write.

Parameters:

  • path (String)

Returns:

  • (Record, nil) —

    nil for a file this gem did not write



149
150
151
152
153
# File 'lib/agent/lock/record.rb', line 149

def read(path)
  parse(File.read(path), path: path)
rescue Errno::ENOENT, Errno::EISDIR
  nil
end

Instance Method Details

#about?(checkout) ⇒ Boolean

Whether this lock is about the files a tree holds: the same repository on the same branch, from anywhere, or this very checkout on this host, whatever branch it was taken on, since switching branches does not make the files on disk somebody else's.

Parameters:

Returns:

  • (Boolean)


253
# File 'lib/agent/lock/record.rb', line 253

def about?(checkout) = lock_key == checkout.lock_key || local_to?(checkout)

#active? ⇒ Boolean

Returns a claim anybody has to respect. An orphaned lock is a message left for whoever comes next, not a claim, so it blocks nobody.

Returns:

  • (Boolean) —

    a claim anybody has to respect. An orphaned lock is a message left for whoever comes next, not a claim, so it blocks nobody.



216
# File 'lib/agent/lock/record.rb', line 216

def active? = !orphaned?

#alive? ⇒ Boolean

Returns the holder's process is still running, on this host.

Returns:

  • (Boolean) —

    the holder's process is still running, on this host



298
299
300
301
302
# File 'lib/agent/lock/record.rb', line 298

def alive?
  return true unless verifiable?

  ProcessInfo.alive?(pid, started_at: started_at, started: started)
end

#blocks?(identity) ⇒ Boolean

Blocking answers "may I claim an overlapping scope": everything except my own lock and my parent's. The one that matters is the sibling: two sub-agents of one session, let loose in the same tree, are exactly the pair this gem exists to keep apart, and treating the whole family as one holder would let them write over each other freely.

A child's lock blocks its parent too. The parent handed that scope out; taking it back while the child is still in there is the same collision from the other direction.

Parameters:

Returns:

  • (Boolean)


295
# File 'lib/agent/lock/record.rb', line 295

def blocks?(identity) = !(mine?(identity) || ancestor_of?(identity))

#expired?(minutes) ⇒ Boolean

Whether the claim is void, so reaping it takes nothing from anybody.

On this host the holder can be asked, and its answer is the only one that counts: a live holder's lock is never expired, however old. Age used to count here too, measured from created_at, so a session two hours into a refactor lost its lock mid-edit and the next agent walked straight in. A holder on another host cannot be asked, so time is all there is, measured from its last write so that notes act as a heartbeat. The same goes for a holder that named no process: a session known by name (session_name:) outlives any one process, so a restart of its host must not void its locks.

Parameters:

  • minutes (Integer) —

    how long an unverifiable lock is trusted

Returns:

  • (Boolean)


318
# File 'lib/agent/lock/record.rb', line 318

def expired?(minutes) = verifiable? ? !alive? : untouched_for?(minutes)

#held_by?(identity) ⇒ Boolean

Two different questions, deliberately not one.

Ownership answers "may I release this, write notes in it, and does mine list it": yes for my own locks and my sub-agents', never for my parent's. A session cleaning up after itself has to be able to take its children's locks with it, or a crashed sub-agent's claim outlives everybody. The reverse is how a child's release-all used to drop the umbrella its parent had just fanned out under.

Parameters:

Returns:

  • (Boolean)


281
# File 'lib/agent/lock/record.rb', line 281

def held_by?(identity) = mine?(identity) || descendant_of?(identity)

#local_to?(checkout) ⇒ Boolean

Whether this lock was taken in this very checkout, on this host. Only then do its frozen paths name files here: the same relative path in another checkout, or on another machine, is a different file.

Parameters:

Returns:

  • (Boolean)


261
# File 'lib/agent/lock/record.rb', line 261

def local_to?(checkout) = tree == checkout.root && same_host?

#lock_key ⇒ String

Returns see Tree#lock_key. A record written before repo and branch were kept has neither, and so falls back to its path on the host that wrote it, which no other host's key can equal.

Returns:

  • (String) —

    see Tree#lock_key. A record written before repo and branch were kept has neither, and so falls back to its path on the host that wrote it, which no other host's key can equal.



244
# File 'lib/agent/lock/record.rb', line 244

def lock_key = Tree.lock_key(repo: repo, branch: branch, root: tree, host: host)

#note(text) ⇒ Record

What the holder has written down since taking the lock.

A lock outlives a reboot; the session that took it does not. Notes are kept in the lock itself, with the same lifespan, so that coming back to a tree after a crash is reading one file rather than guessing.

Parameters:

  • text (String)

Returns:

  • (Record) —

    a copy carrying the note



226
227
228
229
# File 'lib/agent/lock/record.rb', line 226

def note(text)
  body = notes? ? intent : "#{intent}\n\n#{NOTES_HEADING}"
  with(intent: "#{body}\n- #{Time.now.utc.iso8601} #{text.strip}", updated_at: Time.now.utc.iso8601)
end

#notes? ⇒ Boolean

Whether #note ever wrote in this lock. Asked of NOTES_SECTION, the shape note writes, rather than of the heading's words, which an intent can hold without a note under them.

Returns:

  • (Boolean) —

    whether anything worth keeping was written down



236
# File 'lib/agent/lock/record.rb', line 236

def notes? = intent.match?(NOTES_SECTION)

#orphaned? ⇒ Boolean

Returns the holder is gone, but the work it recorded is not.

Returns:

  • (Boolean) —

    the holder is gone, but the work it recorded is not



212
# File 'lib/agent/lock/record.rb', line 212

def orphaned? = status == ORPHANED

#resumed(tree:, scope:, identity:) ⇒ Record

This orphan as a live claim again, held by identity on the branch tree is on now, which need not be the one it was taken on. Its id follows the branch, so the caller has to write it under the new id.

Parameters:

Returns:



201
202
203
204
205
206
207
208
209
# File 'lib/agent/lock/record.rb', line 201

def resumed(tree:, scope:, identity:)
  evidence = identity.evidence
  with(
    id: self.class.id_for(tree, scope), tree: tree.root, repo: tree.repo, branch: tree.branch,
    worktree: tree.worktree?, status: ACTIVE, updated_at: Time.now.utc.iso8601,
    agent_id: identity.id, parent_agent_id: identity.parent_id,
    pid: evidence[:pid], started: nil, started_at: evidence[:started_at], host: evidence[:host]
  )
end

#scope_object ⇒ Scope

Returns:



239
# File 'lib/agent/lock/record.rb', line 239

def scope_object = @scope_object ||= Scope.new(scope)

#stale?(minutes) ⇒ Boolean

A claim still standing, whose holder has not touched it in longer than anybody should need. Reported, never acted on: the holder may be alive and simply slow, so breaking it is a decision somebody announces.

Parameters:

  • minutes (Integer)

Returns:

  • (Boolean)


326
# File 'lib/agent/lock/record.rb', line 326

def stale?(minutes) = active? && untouched_for?(minutes)

#summary ⇒ String

Returns one line, for a listing.

Returns:

  • (String) —

    one line, for a listing



329
330
331
332
# File 'lib/agent/lock/record.rb', line 329

def summary
  where = worktree ? "#{tree} (worktree)" : tree
  "#{scope}\t#{agent_id}\t#{created_at}\t#{where}"
end

#taken_in?(roots) ⇒ Boolean

Whether this lock was taken on this host in one of these checkouts, which is #local_to? for every worktree of a repository at once.

Parameters:

  • roots (Array<String>) —

    see Tree#worktree_roots

Returns:

  • (Boolean)


268
# File 'lib/agent/lock/record.rb', line 268

def taken_in?(roots) = roots.include?(tree) && same_host?

#to_markdown ⇒ String

Returns the file's whole content.

Returns:

  • (String) —

    the file's whole content



188
189
190
191
# File 'lib/agent/lock/record.rb', line 188

def to_markdown
  front = FIELDS.to_h { |field| [field.to_s, public_send(field)] }.compact
  "#{YAML.dump(front)}#{SEPARATOR}\n\n#{intent.strip}\n"
end

#with(intent: self.intent, **changes) ⇒ Record

Returns a copy, since a record on disk is not edited in place.

Parameters:

  • intent (String) (defaults to: self.intent) —

    the body, unchanged unless given

  • changes (Hash) —

    fields to replace

Returns:

  • (Record) —

    a copy, since a record on disk is not edited in place



182
183
184
185
# File 'lib/agent/lock/record.rb', line 182

def with(intent: self.intent, **changes)
  fields = FIELDS.to_h { |field| [field, public_send(field)] }
  self.class.new(**fields, **changes, intent: intent, path: path)
end