Skip to content

About

Portable, zero-dependency multi-agent file-lock system — Exclusive and Team Locks (LOCK*.txt) with scopes, expiry, stale-cleanup, cloud-sync support, and a fast overview cache.

Topics

Resources

Code of conduct

Contributing

Security policy

Stars

1 star

Watchers

0 watching

Forks

Latest commit

 

History

219 Commits

Folders and files

NameName
Last commit message
Last commit date
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

lock-master

lock-master

CI Tests Python 3.10 | 3.11 | 3.12 | 3.13 Platform: Windows | Linux | macOS Code style: Ruff Privacy: Zero-Egress Security: Local-First Security SLA Level 1 SBOM RunAsInvoker Attribution: NOTICE Third-Party Audited Marketing Log Version 1.11.0 License: MIT Contributing: Welcome LLM Indexing Verified ellmos-ai open-bricks

EN | DE | ES | JA | RU | ZH

Portable, zero-dependency multi-agent file-lock system — Exclusive and Team Locks (LOCK*.txt) with scopes, expiry, stale-cleanup, cloud-sync support, and a fast overview cache.

Note

AI / LLM Indexing: AI agents and automated tools can inspect llms.txt for a machine-readable summary, search terms, and disambiguation details. Last checked: 2026-10-03.

🧭 Quick Navigation

  1. Executive Summary & Core Identity
  2. Visual Architecture Topology & Decoupled Layers
  3. End-to-End Multi-Agent Locking & Lifecycle
  4. Target Personas & High-Intent SEO Queries
  5. Comparative Matrix vs. Alternatives
  6. Governance & Runtime Invariants Matrix
  7. Core Capabilities & Lock Types
  8. Start Here & Quick Reference
  9. Quick Start & Common CLI Workflows
  10. Configuration Reference (lock_roots.json)
  11. Optional Watcher UI & REST API
  12. Python API & Extension Points
  13. File Layout, Modules & Shims
  14. Testing, Verification & Quality Gates
  15. Security Policy & Vulnerability SLAs
  16. Third-Party Licenses & Level 1 SBOM
  17. Ecosystem, Sibling Tools & Bundles
  18. Statutory Notice, Liability Limitation & License (§ 521 BGB)

1. Executive Summary & Core Identity

lock-master provides a lightweight, zero-dependency mutual exclusion and coordination protocol engineered for autonomous AI coding agents (Claude Code, OpenAI Codex, Antigravity/Gemini), background worker loops, and human maintainers operating across shared filesystem checkouts.

Instead of introducing heavyweight daemon dependencies or remote lock services, lock-master operates through transparent, human-readable plain-text files (LOCK*.txt). A lock file in any directory signals "this workspace or component is currently occupied" — strictly enforcing that no automated loop or secondary agent may alter files within that scope until the lock is actively released or cleanly expired.

Core Value Propositions

  • 100% Local-First & Zero-Egress: Operates entirely within local filesystem boundaries without network calls, telemetry, or cloud dependencies.
  • Zero External Dependencies: Pure Python standard library (3.10+) for all core locking, scanning, and stale pruning routines.
  • Multi-Agent & Swarm Ready: Built-in intra-host Team Locks (LOCK.team.<host>.txt) with granular sub-claims for files, folders, and MCP tools.
  • Cloud-Sync Resilient: Designed to handle cloud storage latency (OneDrive, Dropbox, Syncthing, Nextcloud) with host-scoped locking and rename-based atomic operations.
  • Fail-Closed Safety: In the event of ambiguity, syntax errors, or unexpired locks, access is strictly denied (read-only safe default).

2. Visual Architecture Topology & Decoupled Layers

The following diagram illustrates the four decoupled operational tiers of lock-master, from CLI/API entry points down to persistent filesystem state and inspection tooling:

flowchart TD
    subgraph T1["Tier 1: Coordination Layer (CLI & API Entry Points)"]
        A["Agent / Automation Start"] --> B["Workspace Scanner: lock_scan.py"]
        C["Atomic Stamping: lock_create.py"] --> D["Workspace Directory"]
        E["Bulk Locking: bulk_lock.py"] --> D
    end

    subgraph T2["Tier 2: Core Mutex Engine & Verification"]
        B --> F{"LOCK*.txt Present?"}
        F -- "No" --> G["Access Granted (Workspace Free)"]
        F -- "Yes" --> H{"Evaluate Lock Type, Expiry & State"}
        H -- "Expired Lock" --> I["Safe Pruning: prune_stale_locks.py --dry-run"]
        I --> J["Atomic Unlink -> Access Granted"]
    end

    subgraph T3["Tier 3: Multi-Agent Concurrency & Team Locks"]
        H -- "Exclusive Lock (Active)" --> K["Access Denied: Wait or Switch Tasks"]
        H -- "Team Lock (Active)" --> L["Evaluate Intra-Host Sub-Claims"]
        L -- "Claim Available" --> M["Atomically Claim File / Tool via team_lock.py"]
        L -- "Claim Contested" --> N["Enqueue in FIFO Waiter Queue"]
        H -- "User / Condition Lock" --> O["Protected Scope: Zero Automated Edits"]
    end

    subgraph T4["Tier 4: Inspection, Watcher UI & Caches"]
        B --> P["Generate Fast Markdown Cache: LOCK-CACHE.md"]
        B --> Q["Optional Localhost Watcher UI: port 8095"]
    end
Loading

Architectural Topology Overview

+--------------------------------------------------------------------------------------------------+
|                                  LOCK-MASTER ARCHITECTURAL TOPOLOGY                              |
+--------------------------------------------------------------------------------------------------+
| [VIEW 1: CLI ENTRY POINTS & AGENT ADAPTERS]                                                      |
|   * CLI Utilities       : lock_scan.py, lock_create.py, prune_stale_locks.py, bulk_lock.py       |
|   * Swarm & Team CLI    : team_lock.py (presence, claims, waiters, broadcast messages)          |
|   * Agent Frameworks    : Claude Code, OpenAI Codex, Antigravity/Gemini, Custom Daemon Loops     |
|   * Zero Dependencies   : 100% Python Standard Library (3.10+), Zero Third-Party Packages        |
+--------------------------------------------------------------------------------------------------+
|                                                |                                                 |
|                                                v                                                 |
+--------------------------------------------------------------------------------------------------+
| [VIEW 2: CORE MUTEX & FENCING LEASE ENGINE]                                                      |
|   * Mutex Discovery     : Scoped active_locks() scan across root & sub-paths                     |
|   * Fencing Leases      : Microsecond Epoch fencing tokens prevent post-TTL stale writes         |
|   * Atomic Stamping     : O_CREAT | O_EXCL / atomic rename prevents race conditions              |
|   * Deterministic TTL   : ISO 8601 timestamps + expires_after relative durations (default 24h)   |
|   * Declarative Rules   : LOCK.permissions.json (deny > ask > allow > default evaluation)       |
+--------------------------------------------------------------------------------------------------+
|                                                |                                                 |
|                                                v                                                 |
+--------------------------------------------------------------------------------------------------+
| [VIEW 3: INTRA-HOST MULTI-AGENT TEAMS & CACHE PERSISTENCE]                                       |
|   * Team Coordination   : LOCK.team.<host>.txt coordinates multi-agent presence & sub-claims     |
|   * FIFO Waiter Queues  : Conflict-free ordered queueing for shared tool & file claims           |
|   * Cache Generation    : LOCK-CACHE.md generated atomically via lock_scan.py --write-cache     |
|   * Optional Watcher    : Localhost SQLite storage (%USERPROFILE%/.lock_watcher) on port 8095    |
+--------------------------------------------------------------------------------------------------+
|                                                |                                                 |
|                                                v                                                 |
+--------------------------------------------------------------------------------------------------+
| [VIEW 4: AIR-GAP, RUNASINVOKER & SECURITY BOUNDARY]                                              |
|   * Security Model      : RunAsInvoker unprivileged execution (Zero UAC/sudo elevation required) |
|   * Network Isolation   : 100% Zero-Egress, Zero-Telemetry, strictly air-gapped local filesystem |
|   * Cloud-Sync Defense  : Rename-based atomic writes immune to OneDrive/Dropbox latency artifacts|
|   * SLA Commitment      : Binding 48h initial security response, 5-day triage, 30-day remediation|
+--------------------------------------------------------------------------------------------------+

3. End-to-End Multi-Agent Locking & Lifecycle

The sequence diagram below shows how two autonomous AI agents coordinate within a shared workspace, handling exclusive locking, contested lock discovery, scoped parallelism, team sub-claims, and safe stale lock recovery:

sequenceDiagram
    autonumber
    actor AgentA as "Agent A (Claude Code)"
    participant LM as "lock-master Engine"
    participant FS as "Local Filesystem / Cloud-Sync"
    actor AgentB as "Agent B (Codex CLI)"
    participant Pruner as "Stale Lock Pruner"

    Note over AgentA,FS: Phase 1: Pre-Execution Lock Check & Exclusive Claim
    AgentA->>LM: Check workspace status: lock_utils.active_locks()
    LM->>FS: Scan for active LOCK*.txt
    FS-->>LM: Workspace clean (0 locks)
    LM-->>AgentA: Access granted (unlocked)
    AgentA->>LM: Stamp scoped lock: lock_create.py --scope api --path api
    LM->>FS: Atomically write LOCK.api.txt (TTL: 24h)
    FS-->>AgentA: Lock confirmed

    Note over AgentB,FS: Phase 2: Contested Access & Scoped Parallelism
    AgentB->>LM: Attempt to modify api module: lock_utils.active_locks()
    LM->>FS: Read LOCK.api.txt (Active, Owner: Claude Code)
    LM-->>AgentB: Access Denied (Contested: api scope locked)
    AgentB->>LM: Switch to docs module: lock_create.py --scope docs --path docs
    LM->>FS: Atomically write LOCK.docs.txt
    FS-->>AgentB: Access granted (Parallel execution)

    Note over AgentA,AgentB: Phase 3: Intra-Host Team Coordination
    AgentA->>LM: Register team presence: team_lock.py presence
    LM->>FS: Atomically write LOCK.team.HOST_A.txt
    AgentA->>LM: Claim file: core/engine.py
    LM->>FS: Record sub-claim in LOCK.team.HOST_A.txt
    AgentB->>LM: Query sub-claims: team_lock.py claims
    LM-->>AgentB: core/engine.py claimed, tests/ available

    Note over AgentA,Pruner: Phase 4: Work Completion & Safe Stale Pruning
    AgentA->>FS: Complete refactoring -> Remove LOCK.api.txt
    alt Abandoned Process or Deadlock
        Pruner->>LM: Execute prune_stale_locks.py --dry-run
        LM->>FS: Inspect creation timestamp vs expires_after threshold
        Pruner->>LM: Execute prune_stale_locks.py
        LM->>FS: Atomically unlink expired LOCK.docs.txt
    else Normal Release
        AgentB->>FS: Remove LOCK.docs.txt upon completion
    end
Loading

4. Target Personas & High-Intent SEO Queries

lock-master is engineered to solve critical concurrency, coordination, and safety bottlenecks across four primary technical user journeys:

[PERSONA-01] Autonomous AI Agent & Multi-Agent Swarm Engineers

  • Profile: Lead AI Engineers, Framework Authors (Claude Code, OpenAI Codex, Antigravity/Gemini) deploying multi-agent swarms over common code checkouts.
  • Pain Points: Heavyweight distributed lock managers (Redis Redlock, etcd, Consul) require running daemon processes, open network ports, credential provisioning, and fail catastrophically in local-first or offline developer workstations. Naive file flags cause race conditions and deadlocks without TTLs.
  • lock-master Solution: Transparent plain-text LOCK*.txt and LOCK.<scope>.txt files readable and writable by any LLM agent or script with zero external dependencies. Autonomous timeout resolution, dry-run stale lock pruning, and hierarchical component scopes allow multiple agents to collaborate in parallel on separate modules without collisions.

[PERSONA-02] Cloud-Sync & Multi-Device Workspace Developers

  • Profile: Cross-device engineers synchronizing code repositories across Workstation, Laptop, and Server nodes using OneDrive, Dropbox, Nextcloud, or Syncthing.
  • Pain Points: Traditional OS kernel locks (flock, fcntl, LockFileEx) are local to a single OS kernel and do not propagate across cloud synchronization providers. Cloud synchronization latency (30s to 5 minutes) creates conflicting edits, split-brain states, and corrupted files.
  • lock-master Solution: Machine-scoped Team Locks (LOCK.team.<host>.txt) with intra-host agent sub-claims and rename-based atomic writes. Remote hosts recognize peer machine locks during sync latency windows and automatically defer file modifications.

[PERSONA-03] Local-First, Zero-Egress & Air-Gapped Tool Builders

  • Profile: Security-sensitive software developers, MCP server authors, and privacy engineers building air-gapped or zero-telemetry workflows.
  • Pain Points: Coordination libraries that phone home, require remote auth tokens, or load bloated dependency trees introduce supply-chain vulnerabilities and fail air-gapped compliance audits.
  • lock-master Solution: 100% Local-First and Zero-Egress by design (INV-LOCAL-01). Executes strictly within unprivileged user mode (RunAsInvoker / INV-SEC-02) with zero external runtime dependencies (dependencies = []), verified through automated AST import audits.

[PERSONA-04] Enterprise Safety, Governance & Compliance Officers

  • Profile: DevSecOps managers, Platform Compliance Officers, and Enterprise Architects requiring strict auditability, non-repudiation, and fail-closed safety.
  • Pain Points: Opaque binary lock databases prevent human inspection. Crashed scripts leave persistent locks that require manual intervention or risky nuclear cleanup scripts.
  • lock-master Solution: Human-readable ISO timestamps, declared owners, and explicit release conditions in plain text. Declarative LOCK.permissions.json rule evaluations with strict priority (deny > ask > allow), deterministic TTL expiration, Level 1 SBOM transparency, and guaranteed dual security SLAs (48h response / 5d triage).

High-Intent Discovery Search Queries

  • multi-agent file locking python zero-dependency
  • claude code codex shared workspace coordination lock files
  • portable local-first mutex for ai coding agents
  • cloud sync resilient locking onedrive dropbox python
  • team lock sub-claims mcp tool mutex
  • fail-closed declarative file lock permissions json
  • safe stale lock pruning python dry-run

5. Comparative Matrix vs. Alternatives

The following matrix compares lock-master against traditional file locking, distributed coordination systems, and database locks across our 10 Governance and Technical Invariants (INV-LOCAL-01 to INV-SLA-10):

# Invariant & Evaluation Dimension lock-master OS Kernel Locking (flock/fcntl) Distributed Lock (Redis Redlock/etcd) DB Advisory Locks (SQLite/PostgreSQL) Ad-Hoc Scripts / Shell Flag Files
1 INV-LOCAL-01: Zero-Egress & 100% Local-First Zero network calls Local kernel only ❌ Requires network daemon ⚠️ Requires DB engine Local files
2 INV-SEC-02: Unprivileged RunAsInvoker Non-root user mode Kernel privilege limits ⚠️ Service daemon credentials DB user privileges User mode
3 INV-FAIL-03: Fail-Closed Default Semantics Deny on error/ambiguity ⚠️ Kernel error returns ⚠️ Split-brain risk on network partition ⚠️ Connection drop behavior ❌ Race conditions / fail-open
4 INV-SCOPE-04: Hierarchical & Scoped Locking Project & component scopes ❌ Single file descriptor ⚠️ Manual key naming ⚠️ Table/row scope only ❌ Fixed file names
5 INV-TEAM-05: Multi-Host Cloud-Sync Tolerance Host-scoped Team Locks ❌ Fails over cloud sync ❌ Not suited for local sync folders ❌ High risk of DB corruption ❌ High race condition risk
6 INV-TTL-06: Deterministic TTL & Dry-Run Pruning Explicit TTL & dry-run ❌ Process lifetime bound ⚠️ Key TTL (no dry-run review) ⚠️ Session bound / connection ❌ Stale locks accumulate
7 INV-PERM-07: Declarative Access Permissions LOCK.permissions.json ❌ OS permissions only ⚠️ ACL / auth policies ⚠️ DB role grants ❌ None
8 INV-AUDIT-08: Human-Readable & Atomic Cache Plain text & LOCK-CACHE.md ❌ Binary kernel state ❌ Opaque binary KV storage ❌ Binary database tables ⚠️ Fragile plain text
9 INV-LIC-09: 100% Permissive Zero-Copyleft MIT License (0% copyleft) OS vendor license ⚠️ BSD / SSPL / Apache ⚠️ Public Domain / PostgreSQL Unspecified
10 INV-SLA-10: 48h Response / 5d Triage SLA Codified formal SLA ❌ Upstream OS vendor ⚠️ Commercial support only ⚠️ Community forums ❌ No maintenance SLA

6. Governance & Runtime Invariants Matrix

lock-master guarantees 10 fundamental runtime and governance invariants across all modules, CLI invocations, and multi-agent coordination layers:

Canonical ID Invariant Title Core Operational Guarantee
INV-LOCAL-01 100% Local-First & Zero-Egress Operates strictly on local filesystems (including local cloud sync mounts like OneDrive/Dropbox). Never transmits telemetry, metrics, or network payloads.
INV-SEC-02 Unprivileged Execution (RunAsInvoker) Runs entirely in standard unprivileged user mode. Never demands administrative elevation, sudo, or root access.
INV-FAIL-03 Fail-Closed Locking Semantics In the presence of ambiguous lock states, parsing syntax errors, or active non-expired locks, access is strictly denied (safe read-only default).
INV-SCOPE-04 Hierarchical & Scoped Locking Root LOCK.txt locks an entire project, while granular LOCK.<scope>.txt allows fine-grained concurrency across disjoint modules.
INV-TEAM-05 Multi-Agent Team Coordination LOCK.team.<host>.txt coordinates intra-host agent teams (presence, file sub-claims, tool claims) while signaling remote hosts to stay out across sync latency.
INV-TTL-06 Deterministic TTL & Stale Cleanup Every lock has an explicit expires_after duration (default 24h); stale locks are safely inspected via --dry-run and atomically pruned.
INV-PERM-07 Declarative Permission Engine Evaluates action intents against LOCK.permissions.json using deterministic priority (deny > ask > allow > default) and regex path matching.
INV-AUDIT-08 Read-Only Inspection & Atomic Cache lock_scan.py is read-only by default; cache exports (LOCK-CACHE.md) are written atomically without altering workspace lock states.
INV-LIC-09 100% Permissive Dependency Stack Zero external runtime dependencies (Python standard library only); development and QA tools are strictly MIT/PSFL/BSD-3-Clause audited.
INV-SLA-10 Dual Security Response SLA Committed 48-hour response and 5-business-day triage window via canonical security contacts ([email protected], [email protected]).

7. Core Capabilities & Lock Types

Lock File Types

  • Exclusive Lock (LOCK.txt): Locks the entire project directory tree for all systems and agents.
  • Scoped Lock (LOCK.<scope>.txt): Locks only a designated subcomponent (e.g. LOCK.api.txt, LOCK.docs.txt), allowing concurrent work on disjoint components.
  • Team Lock (LOCK.team.<host>.txt): Coordinates parallel agents running on the same host system. Combines presence tracking, file/folder claims, MCP/tool locks, and internal message passing in one file. Signals remote machines to back off.
  • User Lock (LOCK.user.txt): Placed directly by human operators. Never automatically expires or pruned; only removable by the human user.
  • Condition Lock (LOCK.condition.<name>.txt): Gates a specific operation until an explicit real-world condition is fulfilled (e.g. release_condition: PR merged). Never expires on time.

File Format Specification

Plain text, key-value pairs formatted as key: value, UTF-8 encoded without BOM:

owner: agent-name-or-human
created: 2026-06-14T10:00
host: workstation
expires_after: 24h
mode: hard
purpose: Refactoring authentication layer
release_condition: PR merged
operations: git-push, deploy
Field Required Example Description
owner Yes claude-code, user Entity holding the lock.
created Yes 2026-06-14T10:00 ISO-8601 timestamp for TTL base calculation.
host Optional WORKSTATION-LG, LAPTOP Machine identifier (useful in multi-device setups).
expires_after Optional 24h, 90m, 2d TTL duration string (default: 24h). Ignored for user/condition locks.
purpose Optional Refactoring auth module Human-readable explanation of current task.
mode Optional hard | soft hard = no modifications (default); soft = read-only hints.
release_condition Optional* All tests passing in CI Required for condition locks.
operations Optional publish, push Comma-separated gated operations; unlisted actions remain permitted.

8. Start Here & Quick Reference

Common Need Recommended Action Command / Usage
Prevent simultaneous agent edits on a repo Stamp root exclusive lock python lock_create.py <project>
Enable parallel agent work on separate modules Stamp scoped component lock python lock_create.py <project> --scope api --path api
Scan active locks across all project roots Run read-only scanner python lock_scan.py
Export human-readable Markdown status page Generate lock cache python lock_scan.py --write-cache
Inspect expired/abandoned locks safely Preview stale locks python prune_stale_locks.py --dry-run
Safely remove verified expired locks Execute stale pruning python prune_stale_locks.py
Coordinate multi-agent swarm on one machine Create host team lock python lock_create.py <project> --team <HOST>

Claude Code plugin ellmos-lock-master

This repository is also a Claude Code plugin. It makes Claude respect the locks of other agents automatically:

  • Hooks: before every Edit, Write, MultiEdit or NotebookEdit, and before git push (through Bash or PowerShell; the PowerShell tool's Set-Content, Remove-Item, Move-Item, >, Expand-Archive/Compress-Archive -DestinationPath, Invoke-WebRequest/Invoke-RestMethod -OutFile, Export-Csv, cmd /c del|erase|rd, robocopy, xcopy, git checkout -- <paths>, git restore and git clean and the like count as edits, and what cannot be read without running it is denied when a foreign lock covers the working directory -- such a path from a free directory into a locked one, a variable or pipeline input, is not seen, as in Bash), the plugin checks the target with active_locks_for_path() and denies the call when a foreign active lock covers it, or when another agent has claimed the file on the team board. A push also sees a foreign lock below the repository root when the pushed commits change a path in its area (named refspecs, --tags, --all and --follow-tags are read from git log; for any other form the tree is walked, the worktree and its main clone within 8 s together, and what cannot be determined in time is denied, a branch deletion in a tree too large to walk with the hint to ask the user). At session start it lists the locks that affect the working directory and names the session.
  • MCP server lock-board: read the team board, post notes, claim and release files (see below).
  • Commands: /ellmos-lock-master:lock, /ellmos-lock-master:unlock, /ellmos-lock-master:locks, /ellmos-lock-master:message.
  • Skill: lock-protocol (when to lock, lock types, fencing, release).

Known open ways. The hook guards against accidental writes and pushes; it is no sandbox. It reads commands whose targets are literal; these it does not see, on purpose:

  • writes from code it does not run: python -c "open(...)", node -e, New-Object IO.StreamWriter and other .NET objects (only [IO.File]:: and [IO.Directory]:: calls count), a script file -- reading code is no guard's job. The same holds for a push: one in a script file the line runs, by name or through standard input (bash x.sh, cat x.sh | sh, Get-Content x.ps1 | pwsh -), is not seen, only a push named in the line itself;
  • obfuscated commands: cmd /c g^it pu^sh, cmd /c d^el x (cmd.exe removes ^, the letters never appear in the text), a push spelled without its letters (a variable, a git alias, a script);
  • file writes in the Bash tool (only its pushes are checked), and a path that is not literal from a free working directory into a locked one (a variable, pipeline input);
  • a recursive write to a folder (Remove-Item -Recurse, robocopy /MIR, git clean of a folder) is checked against the locks on that folder and above it, not against locks in its subfolders;
  • what a push publishes is read against the remote-tracking refs of this clone: -f/--force/+ against a stale one (what others pushed since the last fetch; fetch first or use --force-with-lease), a fetch refspec other than the default, --all/--branches without force for the branches other than HEAD's, a branch whose tracking ref is gone, and a refspec without colon that push.default=upstream maps to another branch;
  • a program that runs the text it is given but is not on the guard's list of runners (RUNNERS in plugin/lock_guard.py: shells, wrappers such as nohup/sudo/sg/xargs/ssh, interpreters, make/npm, tar/gtar, man, ex/ed, sqlite3, wmic, Add-Type, New-Object, the ScheduledTask cmdlets, the keywords for/select/foreach, builtins such as alias/trap; options such as --sh-exec): text naming a push in its arguments reads as data;
  • a function, an alias or a command lookup changed in a way the guard does not read. It reads names and fixed forms: definitions by command name (function, alias, Set-Alias, Set-Item ..., also behind builtin/command and bash's keywords: if alias ...; then), a command word known only at run time ($x '...'), bash name (), hash, trap, source/., enable and PATH set by an assignment (PATH=.:$PATH, not echo PATH=x) or a builtin (export/declare/local/let PATH=..., a nameref declare -n p=PATH, read/mapfile PATH, printf -v PATH, unset PATH); PowerShell's function:, alias: and variable: drives (also provider-qualified, ...\Alias::x, in an array, -Path x.txt,function:x, and after a parameter's colon, -Path:function:x), a new drive (New-PSDrive/ndr/mount), $PSDefaultParameterValues, Get-Variable, $ExecutionContext, [scriptblock] (also [ scriptblock ]), Import-Alias, New-Module/Import-Module/Import-PSSession, dot-sourcing and & of a variable or an expression (& $c, & (Get-Command Set-Al*)). A blank right after a drive's colon is prose ("alias: ...", PowerShell defines nothing there; it trims other blanks, so 'function:x ' counts). Not seen: a provider path built at run time (New-Item -Path ('func'+'tion:Sort-Object')), a function that a PowerShell script run in the line defines globally (./x.ps1 with function global:Sort-Object), the shell profile, an auto-loaded module, a PATH that already holds . or another folder the line writes to, an arithmetic assignment with blanks ((( PATH = 0 )));
  • text kept somewhere other than a file, a variable or a transcript (the registry, an environment variable set through .NET) and run by a program other than iex/Invoke-Command/eval;
  • a file that a later call runs without naming it: text about a push written to the PowerShell profile ($r | Out-File $PROFILE, ... > $PROFILE), a git hook (... > .git/hooks/pre-push), the git config or a shell start-up file is data for the line that writes it. The guard reads one call at a time; the call that later loads the file does not name the push;
  • writes that are no edits to the guard: cmd /c with copy, move or a redirect (cmd /c "echo x > f"; only del/erase/rd count), git checkout <path> and git checkout HEAD~1 <path> without --, git reset --hard, git stash, and a branch switch (git checkout main, git switch), which rewrites the work tree.

Text about a push is no push: agy -p "... Do NOT run git push ...", usmc note "... git push ..." or rg "git push" pass, with or without a lock. That holds for an argument with a blank in it, given to a program named bare or by a path to an .exe, with no runner, -c/-e/--command-style option (also with its value attached: --exec="...", -c"...") or script in front of it and no PowerShell block that runs code; every later pipeline stage must be a data command or a pure filter (head, tail, wc, cut, sort without -o/--compress-program, uniq without file arguments, Out-String, Select-Object, Sort-Object, Measure-Object) with no $(...) or block that runs code; when the output goes into a file or a variable (> log.txt, | tee log.txt, | Tee-Object log.txt, $r = ..., -OutVariable), nothing else in the line may run anything (data commands, cd, PowerShell's Out-File, if (...) {...} with such blocks and a variable or its property, $r.Count, are fine); and the line defines no function or alias (sort() { sh; }, function Sort-Object {...}, Set-Alias, $PSDefaultParameterValues, see the open ways above for what is read) and has no iex/Invoke-Command/eval/Start-Transcript. Otherwise, as before, the line is not understood and a push in it is unresolved (bash -c "git push", eval "...", nohup sh -c "...", ./run.sh "git push", npm run push, agy -p "..." | sh, ... | dd of=x.sh; sh x.sh, ... | Out-File x.ps1; ./x.ps1).

In PowerShell, relative paths follow each literal cd of the line's top level to an existing folder; after any other cd (a variable, cd -, one inside a block or $(...)) they are unclear, and the folders the literal cds lead to are checked against locks too (no lease, no board claim). A script, ./& with a script path and iex may change the location, also inside $(...): a push in such a line is denied, as an unresolved one. PowerShell runs $(...), (...), blocks and every pipeline stage in the line's process, so code there may move a push as well ($env:GIT_DIR = ..., [Environment]::SetEnvironmentVariable(...), New-Item env:GIT_DIR ... | Out-Null): a push is resolved only when these run data commands and listed built-in Get- cmdlets alone (Get-Date, Get-Content, ...; an unlisted Get- name may be an alias, function or module command and is denied; a profile or module that shadows a listed one stays open) (a stage may also be git, a pure filter, Out-File or ForEach-Object {...}): Write-Output $(Get-Date) before a push passes, Write-Output "$(git branch --show-current)" is denied. Only the bare names count: cd.exe, Set-Location.exe and Out-File.exe are programs on PATH, not the cmdlets, and bash's cd is the word cd alone (CD, /usr/bin/cd move nothing).

Install from the ellmos marketplace:

/plugin marketplace add ellmos-ai/ellmos-plugins
/plugin install ellmos-lock-master@ellmos

Team board and file claims: at session start the plugin shows the presence entries and the latest five messages of this host's team lock (LOCK.team.<HOST>.txt, written by team-lock/team_lock.py) and names the session: claude-code@<HOST>.<sid8>. That name is the session's lock owner (/ellmos-lock-master:lock uses it) and its agent name on the board; /ellmos-lock-master:message <text> posts a note for the other agents on the same host. The bundled MCP server lock-board (.mcp.json, started as git -c alias.lock-board=!sh lock-board hooks/run.sh mcp: Claude Code starts MCP servers directly, not through Git Bash, and on Windows sh is usually not on PATH, while git, which Claude Code requires there, runs ! aliases in its own sh; Python standard library only, every write goes through team-lock/) offers five tools: board_read (presence, claims, queue, latest messages), board_post, board_claim (with queue=true you wait in line, first come first served), board_release and board_presence. Pass your session name as agent. If another agent holds an EDITING claim on a file or folder, the PreToolUse hook denies edits below it, names the holder and your place in the queue, and points to /ellmos-lock-master:message and board_claim; a claim of your own session (or of the shared claude-code@<HOST>) passes, and so does every path nobody claimed. Claims are explicit: there is no automatic claim at the first edit, because a session that crashes would leave claims nobody releases (claims have no expiry of their own). A normal session end releases the session's claims and presence; after a crash the lines are removed by hand or lapse with the team lock. A claims section that cannot be parsed does not block (the team lock still lets the host's agents in); the hook says so. Claims are a cooperative signal between agents, not a security boundary: agent names are self-declared, and Bash writes are not recognised. The MCP server does not know the session id (Claude Code documents no session variable for MCP servers), so the board tools act as the agent you pass, or as the shared claude-code@<HOST> when you pass none; enforcement lives in the hook, which does receive the session id.

Fencing in the hook: every lock carries a fence number, a grant number from the clock that lock_create hands out. The hook checks it for locks whose owner is a shared prefix (claude-code@<HOST> or ELLMOS_LOCK_OWNER), because several sessions of one host can hold such a lock without noticing each other. The first time a session relies on one, it remembers the fence (a small JSON file in the temp directory, ELLMOS_LOCK_STATE_DIR, removed at session end). If the lock later carries another fence, an earlier one or none at all, it was granted anew (after expiry, --force, or by a parallel session with the same owner string) and the hook stops treating it as the session's own: edits are denied with the reason of fence_status() and the advice to release it and set it again with /lock under the session name. A lock named after the session needs no check, no other session carries that name. What this is not: it is cooperative detection, not enforcement. It happens before each tool call, so a lock lost between the check and the write goes unnoticed (see the note in pure-locking/lock_utils.py); a session that first looks at the lock after the takeover trusts what it finds; team locks are shared by design and are not fence-checked; fence numbers are clock based. If the state file cannot be written, the hook falls back to trusting the lock, as before 1.8.

Codex and Kimi Code: python plugin/lock_guard.py pretooluse --actor codex|kimi is the same guard for the two other agents here that run PreToolUse hooks. It reads Codex's apply_patch (paths from the *** Add File:, *** Update File:, *** Delete File: and *** Move to: header lines; a patch whose targets cannot be read is denied), Kimi's Write and Edit (the names in the tool schema of Kimi Code CLI 0.14.2, field path) and WriteFile, StrReplaceFile, DeleteFile and MoveFile, and git push through Bash (Codex); it denies with exit code 2 and the reason on stderr, the contract both hosts honour. Owner prefix and session name follow the actor (codex@<HOST>, kimi@<HOST>.<sid8>). The payload shapes are those of the documented hook contracts as implemented and tested in workflowhooker's action guard; this release tests them with those payloads, not inside a live Codex or Kimi session. hook-master install-snippet --id lock_edit_guard --provider codex|kimi|claude prints the configuration fragment (it never edits a host configuration; the fragment goes through hook-master's library/lock_edit_guard.py, a connector that runs this lock_guard.py, and binds the edit tools only, git push stays with the existing lock_push_guard); calling this repository's guard directly, with git push through Bash as well, it is

{"hooks": {"PreToolUse": [{"matcher": "^(apply_patch|Bash)$", "hooks": [{"type": "command",
  "command": "python -X utf8 \"/path/to/lock-master/plugin/lock_guard.py\" pretooluse --actor codex", "timeout": 10}]}]}}

for ~/.codex/hooks.json and

[[hooks]]
event = "PreToolUse"
matcher = "Write|Edit|WriteFile|StrReplaceFile|DeleteFile|MoveFile"
command = "python -X utf8 \"/path/to/lock-master/plugin/lock_guard.py\" pretooluse --actor kimi"
timeout = 10

for ~/.kimi-code/config.toml. The tool names are those in the tool schema of Kimi Code CLI 0.14.2 (read from its session logs: Write and Edit with path, shell tool Bash with command); WriteFile and the other older names stay bound for older versions. The fragment does not bind Kimi's Bash, so Kimi's git push is not guarded here; adding Bash to the matcher would cover it (proposal, not done: the existing lock_push_guard covers pushes for the other hosts). Antigravity (agy) cannot be bound: according to hook-master's provider model it only has PreInvocation (before the model call, without a tool target); it keeps to the LOCK*.txt convention by instruction (not verified against a live agy installation, this host has no agy hook configuration). Why hook-master leaves PreToolUse out of its default snippets is explained in its README.

Optional leases across computers (preview, not yet available to the public): they need the roshambo package, which is not published yet. Without ELLMOS_LOCK_LEASES nothing of this is active and the plugin works exactly as described above. Enter the lease store in the plugin option lease_store (Claude Code asks for it when the plugin is enabled and keeps it in the system's credential store, because a database URL can hold a password), or set ELLMOS_LOCK_LEASES; the option wins when both are set. The value is a lease store of ellmos-roshambo (roshambo.lease_store): sqlite:///path/leases.db for one computer, postgresql://... for a self-hosted database that several computers share. Every edit then also takes a per-file lease for the session (ELLMOS_LOCK_LEASE_TTL, default 900 s, renewed by each edit of the file). An edit of a file whose lease another session holds is denied with holder, host and intent; the session's leases are released at session end. The key is the repository origin plus the path inside it, so clones on different computers, worktrees and branches share it. With the variable set and the roshambo package missing, edits are denied (fail closed). A lease store that cannot be reached (reboot, VPN down; connect timeout 5 s) does not stop work: the edit goes through with a warning, and file locks are still checked.

Data flow: local files only. The hooks read LOCK*.txt files in the target directory, its parents and a worktree's main clone, and call git to resolve worktrees. Nothing is sent over the network unless you switch leases on; then lease key (repository origin and file path), host, session id and tool name go to the lease store you configured. Ownership: a lock is the session's own when its owner is the session name claude-code@<HOST>.<sid8> or starts with claude-code@<HOST> or a prefix in ELLMOS_LOCK_OWNER (then fence-checked, see above); team locks of the same host are shared. Internal errors deny the call; ELLMOS_LOCK_FAIL_OPEN=1 allows instead. Python 3.10+ is required (py -3 on Windows, or set ELLMOS_PYTHON).

Compatibility: Claude Code (hooks, commands, skill, MCP server). The LOCK*.txt convention is readable by Codex, Gemini, Kimi and humans; Codex and Kimi Code can run the same guard as a hook (above), Gemini/agy cannot. Privacy and support: https://ellmos-ai.github.io/plugins.html.

Examples:

  1. Another agent holds LOCK.txt in docs/. Ask Claude to edit docs/guide.md: the edit is denied with the holder, host and purpose of the lock, and Claude reports it instead of working around it.
  2. /ellmos-lock-master:lock parser src "refactor parser" before a larger change, /ellmos-lock-master:unlock afterwards; other agents see the lock and leave src/ alone in the meantime.
  3. git push from a repository with an active LOCK.user.txt (for example a frozen competition entry) is denied, while edits and pushes in unlocked repositories run as usual.

9. Quick Start & Common CLI Workflows

1. Copy or Install Scripts

Everything required for standard locking operations resides in pure-locking/:

pure-locking/lock_utils.py
pure-locking/lock_scan.py
pure-locking/prune_stale_locks.py
pure-locking/LOCK_TEMPLATE.txt

Place them side-by-side in your tooling directory or use the repository root shims.

2. Check Lock Status Before Starting Work

# Check if current directory is locked
python lock_scan.py --check-dir .
echo $?  # 0 = free to work; 1 = locked

3. Stamp a New Lock

# Exclusive project lock
python lock_create.py /path/to/project --owner "claude-code" --purpose "Refactoring core parser"

# Scoped component lock
python lock_create.py /path/to/project --scope frontend --path frontend --owner "codex" --purpose "UI redesign"

4. Scan Workspace Hierarchy

# Human-readable console summary
python lock_scan.py

# Machine-readable JSON output for automated pipelines
python lock_scan.py --json

5. Safe Pruning of Stale Locks

# Preview what would be unlinked without making changes
python prune_stale_locks.py --dry-run

# Atomically prune expired locks
python prune_stale_locks.py

10. Configuration Reference (lock_roots.json)

To scan multiple project hierarchies, copy pure-locking/lock_roots.example.json to lock_roots.json:

{
  "default_max_depth": 4,
  "shallow_depth": 2,
  "skip_dirs": [".git", ".venv", "node_modules", "__pycache__", "build", "dist"],
  "roots": [
    { "path": "C:/_Local_DEV/repos" },
    { "path": "C:/Users/user/OneDrive/Projects", "shallow": true }
  ],
  "caches": [
    {
      "name": "system-wide",
      "path": "C:/_Local_DEV/state/LOCK-CACHE.{host}.md"
    }
  ],
  "twin_resolution": {
    "clone_roots": ["C:/_Local_DEV/repos"],
    "index_path": "C:/Users/user/OneDrive/Scripts/TWIN-INDEX.{host}.json"
  }
}
Key Type Default Description
default_max_depth int 4 Maximum directory recursion depth for standard roots.
shallow_depth int 2 Depth limit applied to roots marked "shallow": true.
skip_dirs string[] [] Subdirectory names completely excluded from directory traversal.
roots object[] [] List of { "path": string, "shallow": bool } definitions.
caches object[] [] Output destinations for Markdown status cache files.
twin_resolution object absent Optional clone roots and host-specific twin index; unresolved mapping blocks --check-dir with exit 1.

11. Optional Watcher UI & REST API

For visual fleet monitoring, pure-locking/watcher/ provides an optional localhost dashboard and REST API binding strictly to 127.0.0.1:8095:

# Launch background cache daemon
python pure-locking/watcher/lock_watcher.py --update-cache

# Launch localhost Web server
python pure-locking/watcher/web_server.py --port 8095

Navigate to http://127.0.0.1:8095 to inspect active locks, component room maps, live timelines, and execute safe dry-run prunes.


12. Python API & Extension Points

Direct programmatic integration via lock_utils:

from pathlib import Path
from datetime import datetime
import lock_utils

project_dir = Path("/path/to/my-repo")

# 1. Check workspace locking status
active = lock_utils.active_locks(project_dir)
if active:
    print(f"Workspace locked by active files: {[str(p.name) for p in active]}")
else:
    print("Workspace is free for modification.")

# 2. Parse lock metadata
lock_data = lock_utils.parse_lock_file(project_dir / "LOCK.txt")
print(f"Owner: {lock_data['owner']}, Created: {lock_data['created']}, Purpose: {lock_data['purpose']}")

# 3. Check expiry
if lock_utils.is_expired(project_dir / "LOCK.txt", now=datetime.now()):
    print("Lock has expired according to its TTL duration.")

13. File Layout, Modules & Shims

lock-master is structured as a stack of three decoupled sub-modules, unified with flat compatibility shims at the repository root:

lock-master/                        # Shipped as ONE modular repository
├── pure-locking/                   # Core locking, scanning, and pruning engine
│   ├── lock_utils.py               # Core library: parse, scope, expiry, team-lock helpers
│   ├── lock_scan.py                # CLI: list active locks, write cache
│   ├── prune_stale_locks.py        # CLI: remove expired locks (--dry-run support)
│   ├── lock_create.py              # CLI: build correct lock filename and header
│   ├── bulk_lock.py                # CLI: lock/unlock multiple project roots
│   ├── watcher/                    # Optional localhost daemon, REST API, and Web UI
│   ├── LOCK_TEMPLATE.txt           # Template for exclusive locks
│   ├── TEAM_LOCK_TEMPLATE.txt      # Template for multi-agent team locks
│   └── lock_roots.example.json     # Example scanning configuration
├── permission-control/             # The LOCK.permissions.json rule engine
│   ├── permissions.py              # allow / deny / ask intent evaluation
│   └── LOCK_PERMISSIONS_TEMPLATE.json
├── team-lock/                      # Team-Lock CLI & intra-host concurrency
│   ├── team_lock.py                # CLI entry point for team claims & queues
│   └── _lock_master_team/          # FIFO queue, OS advisory guard, atomic writes
│
├── lock_scan.py                    # Root compatibility shim
├── lock_utils.py                   # Root compatibility shim
├── lock_create.py                  # Root compatibility shim
├── bulk_lock.py                    # Root compatibility shim
├── prune_stale_locks.py            # Root compatibility shim
├── permissions.py                  # Root compatibility shim
├── team_lock.py                    # Root compatibility shim (CLI: lock-master-team)
│
├── LOCK-SYSTEM.md                  # Canonical lock specification & lifecycle
├── NOTICE                          # Legal attribution notice (Lukas Geiger, ellmos-ai, open-bricks)
├── THIRD_PARTY_LICENSES.md         # Level 1 SBOM, license audit & invariant matrix
├── THIRD_PARTY_LICENSES.txt        # Plain-text companion Level 1 SBOM inventory & full license texts
├── MARKETING-LOG.txt               # Personas, SEO queries & competitive analysis
├── SECURITY.md                     # Security policy, dual SLAs & vulnerability disclosure
├── llms.txt                        # AI agent discovery context & metadata
├── pyproject.toml                  # PEP 517/621/639 configuration (dependencies = [])
└── tests/                          # Automated contract and regression test suite

14. Testing, Verification & Quality Gates

Run the comprehensive pytest test suite locally:

# Run all unit, functional, and metadata contract tests
python -m pytest tests/ -v

# Run Ruff linting check
python -m ruff check .

Our continuous integration matrix validates:

  • Multi-OS execution (Ubuntu, Windows, macOS).
  • Python matrix (3.10, 3.11, 3.12, 3.13).
  • Bytecode compilation verification gate (python -m compileall -q .).
  • Isolated wheel packaging smoke tests.
  • 100% strict lint compliance via Ruff.

15. Security Policy & Vulnerability SLAs

Security disclosures are handled under strict zero-egress, local-first protocols. See SECURITY.md for vulnerability disclosure guidelines, PGP keys, and our dual SLA commitments:

  • Initial Response SLA: Within 48 hours ([email protected], [email protected]).
  • Triage & Assessment: Within 5 business days.
  • Remediation Target: Fixes deployed within 30 calendar days.

16. Third-Party Licenses & Level 1 SBOM

lock-master enforces a strict Zero-Runtime-Dependency Guarantee (dependencies = [] in pyproject.toml) and is built exclusively with permissive open-source licenses (MIT, Apache-2.0, PSFL, BSD-3-Clause). It contains zero GPL or restrictive copyleft code.

For the complete Level 1 Software Bill of Materials (SBOM), audited dependency matrix, and Invariant Cross-Reference Matrix (INV-LOCAL-01 to INV-SLA-10), see THIRD_PARTY_LICENSES.md and the standalone plain-text companion THIRD_PARTY_LICENSES.txt.


17. Ecosystem, Sibling Tools & Bundles

lock-master is a foundational synchronization and locking pillar within the ellmos-ai ecosystem and the umbrella open-bricks open-source collective:

Sibling Tool Organization Role & Capabilities
ticket-master ellmos-ai Autonomous ticket routing and task dispatching triage console
agent-ops-stack ellmos-ai Fetches this repository from its manifest and reports the declared locking role; follow this project's instructions for setup.
clutch ellmos-ai Adaptive multi-model LLM router & agent execution gear
coma ellmos-ai Manages local job files and starts agent processes or records their status through a file protocol; it does not limit those processes' network access or operating system rights
swarm-ai ellmos-ai Swarm intelligence and autonomous agent consensus engine
gardener ellmos-ai Local-first autonomous session and context memory engine
system-gap-master ellmos-ai Serverless multi-agent workspace synchronization & reconciliation
system-explorer ellmos-ai Evidence-based function resolution & component drift auditor
open-compute-mcp ellmos-ai Safe operator interaction, signal overlay & MCP computing bridge
ellmos-filecommander-mcp ellmos-ai High-performance filesystem & workspace operations MCP server
ellmos-codecommander-mcp ellmos-ai Semantic code analysis, AST inspection & refactoring MCP server
n8n-manager-mcp ellmos-ai Safety-gated n8n workflow management & automation orchestrator
prompt-evidence-collector ellmos-ai Audit-ready LLM interaction capture & cryptographic evidence store
policy-registry ellmos-ai Unified agent permission and policy management engine
sqlite-transit-sync ellmos-ai Multi-agent state synchronization via SQLite WAL journals
workflowhooker ellmos-ai Event hooks and agent workflow automation triggers
memoryhooker ellmos-ai Transparent SQLite/FTS5 working memory capture for agents
DevCenter dev-bricks Developer control plane, repository dashboard & environment manager
CodeBox dev-bricks Polyglot code snippet manager & developer workbench
safe-start-for-codex dev-bricks Safe starter and permission isolator for Codex CLI sessions
automation-master dev-bricks Automation orchestration and local job scheduler
CleanMarkdown doc-bricks Markdown formatting, linting, and structural sanitization toolkit
PDFtoPDFocr doc-bricks PDF OCR processing, searchable text layer embedding & validation
open-bricks open-bricks Umbrella catalog & cross-ecosystem architectural registry

18. Statutory Notice, Liability Limitation & License (§ 521 BGB)

Statutory Notice & Limitation of Liability (§ 521 BGB)

The provision of this software is made free of charge as a statutory courtesy (Gefälligkeit / unentgeltliche Schenkung pursuant to § 521 BGB of the German Civil Code). Under German statutory law, liability of the author and contributors is strictly limited to intent and gross negligence (Vorsatz und grobe Fahrlässigkeit).

License

This project is licensed under the terms of the MIT License. See LICENSE and NOTICE for complete copyright attribution.

About

Portable, zero-dependency multi-agent file-lock system — Exclusive and Team Locks (LOCK*.txt) with scopes, expiry, stale-cleanup, cloud-sync support, and a fast overview cache.

Topics

Resources

Code of conduct

Contributing

Security policy

Stars

1 star

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages