Skip to content

Latest commit

 

History

History
517 lines (420 loc) · 21.8 KB

guide.md

File metadata and controls

517 lines (420 loc) · 21.8 KB

Guide

How to do the common tasks with square². Every command is run from the top of the repository as node tools/square2/bin/square2.mjs <command> when the tool is vendored at tools/square2; the text below writes square2 <command> for short. The reference lists every key, command and code; the trust model says why the steps are as they are.

The starter model has its own guide, .square2/README.md, which travels with the vendored copy (templates/consumer/.square2/README.md in this repository). It holds a worked example and the same steps as this page.

Adopt the tool in a repository

You need Node.js 22 or later and git 2.40 or later for the judge.

  1. Copy the templates of square² (templates/consumer/) into the repository: .square2/, .githooks/pre-push and the three workflows under .github/workflows/.

  2. Replace every value marked CONSUMER in the workflows and the hook, and the example values of the starter model: branch, approvers and protected of .square2/policy.json, and the settings of .square2/review.json. If the vendored path is not tools/square2, change it in policy.json, in the hook and in all three workflows.

  3. Vendor the tool from a checkout or a clone URL of square² and a revision:

    node <square2 checkout>/bin/square2.mjs vendor --from <path|git-url> --ref <rev>

    It copies the tool into the vendored_path of policy.json and writes .square2/lock.json.

  4. Run the check. With no guardrail yet it passes:

    node tools/square2/bin/square2.mjs check
  5. Turn the parts on: the repository variables SQ2_GATE_ENABLED and SQ2_REVIEW_ENABLED (any value other than true turns a workflow off), and the hook with git config core.hooksPath .githooks.

  6. Choose one of the two jobs of square2-judge.yml and delete the other with its event:

    • judge (event pull_request_target), for a private repository whose default branch is the integration branch. GitHub takes the workflow file from the default branch, so the job runs only on pull requests opened after the file is there. Land square2-judge.yml first, in a pull request of its own; then open the adoption pull request (the one that adds .square2/policy.json). On it the job prints [S2-ADOPTION] and passes.
    • judge-pr (event pull_request), for a repository where the first event is not available. It runs on the adoption pull request itself, prints [S2-ADOPTION] and passes. It is weaker: a pull request can change it.
  7. Make the judge job a required status check of the integration branch once it has reported on a pull request (a required check that never runs blocks every merge). Make the job check of square2-gate.yml a required check too: the judge does not see a removed anchor line or a changed fixture, and check does.

  8. Guard .square2/ with a review rule of the host, for example an owners file with a required review by the approvers. An approval is an entry of .square2/approvals.json, and adding one is free for the judge, so this rule decides who can approve.

  9. List in protected of the policy what the judge must compare by bytes: the configuration files of your engines when they have their default names (for example eslint.config.mjs), the scripts that a command guardrail runs from a directory, and every other file that your guardrails depend on. Every glob of protected must match a file.

The hook checks only a pushed commit that is the clean checked-out HEAD; any other push gets one notice and is checked by CI. git push --no-verify skips the hook.

Add a guardrail

A guardrail is a record of .square2/guardrails.json. Adding one, with its fixtures and the decision that its proof points to, is free for the judge, and so is raising its state.

Choose the state

State What happens
proposed nothing runs; the record may have no proof yet
observe it runs; its findings are printed on standard error with the prefix advisory and never fail the check
enforce it runs; a new finding fails the check with exit 1

Start a new guardrail in observe when the tree may already break its law, read its findings, then raise it to enforce. When it moves to enforce, every finding it has is new unless the same change adds it to the baseline, and that needs an approval (see "Accept a finding" below).

Write the record, the fixtures and the proof

This example keeps console.log( out of src/. It is the same as the worked example of the starter model.

  1. Write the decision that the proof points to, in a file that matches anchors of the policy (the starter allows .square2/*.md). The anchor line stands directly above the heading, at the first column, outside a fenced code block. .square2/decisions.md:

    # Decisions
    
    <a id="no-console"></a>
    ## Application code does not write to the console
    
    The application logs through its logger, so that every line has a level and a context.
  2. Add the record to .square2/guardrails.json. The list is sorted by id, and the file is canonical JSON with two-space indentation:

    {
      "schema_version": 2,
      "guardrails": [
        {
          "id": "APP-NO-CONSOLE",
          "kind": "engine",
          "state": "enforce",
          "layer": "gate",
          "class": "invariant",
          "level": 2,
          "owner": "your-team",
          "law": "Application code does not write to the console.",
          "proof": {
            "kind": "decision",
            "anchor": ".square2/decisions.md#no-console"
          },
          "check": {
            "engine": "pattern",
            "options": {
              "pattern": "console\\.log\\("
            }
          },
          "scope": [
            "src/**"
          ],
          "instead": "use the logger of the application"
        }
      ]
    }
  3. Add the fixtures. .square2/fixtures/APP-NO-CONSOLE/bad/src/app.js holds a file on which the guardrail must fire, .square2/fixtures/APP-NO-CONSOLE/good/src/app.js one on which it must not. The globs of scope are read inside each tree.

    console.log("hello");
    export const hello = "hello";
  4. Add the files to git with git add. The file of a decision must be tracked; an untracked one is [S2-MODEL] ... which is not tracked.

  5. Run the self-test and the check:

    node tools/square2/bin/square2.mjs selftest
    node tools/square2/bin/square2.mjs check

    The self-test runs every planned engine guardrail on its bad tree and expects a finding, and on its good tree and expects none; check runs the self-test first. A failure is [S2-SELFTEST], exit 2. A file of src/ that breaks the law then fails the check:

    [APP-NO-CONSOLE] src/app.js:1 matches console.log( — Instead: use the logger of the application
    square2: failed (1 new, 0 stale)
    

square2 explain --guardrail APP-NO-CONSOLE prints the state, law, proof and fix of the guardrail; square2 explain src/app.js prints what the model says about a path.

A proof by a failure

When a guardrail is made for a defect that happened, its proof can be that defect: a commit that introduced it and a replay report that shows the guardrail fires on that commit and not on its first parent. replay --guardrail reads the record from the model, so the model must load first.

  1. Add the record in the state proposed with "proof": null, and add its fixtures. A record in proposed runs nowhere and needs no proof, so the model loads.

  2. Replay the guardrail on the commit. replay runs it in enforce in a temporary worktree and does not touch the work tree. It writes no directory, so make .square2/replay/ first:

    mkdir -p .square2/replay
    node tools/square2/bin/square2.mjs replay --guardrail APP-NO-CONSOLE --commit <sha> --out .square2/replay/APP-NO-CONSOLE.json

    It prints, for example, replay APP-NO-CONSOLE on dd7fd1f90a5a: fires, parent 1a4d47794cb6 does not fire, fires newly.

  3. Set the proof and the state, and track the report with git add:

    "state": "enforce",
    "proof": {
      "kind": "failure",
      "commit": "<sha>",
      "replay": ".square2/replay/APP-NO-CONSOLE.json"
    }

    A first proof where the record had none, and a higher state, are free for the judge. A changed or removed proof of a guardrail that has landed needs an approval.

The commit must be in the history of HEAD, so a job that loads the model needs the full history (fetch-depth: 0). A guardrail that already fires on the parent takes a decision proof.

To try a guardrail before it is in the model, replay it from a file outside the model, with its fixtures in a directory that holds bad/ and good/:

node tools/square2/bin/square2.mjs replay --candidate /tmp/c/guardrail.json --fixtures /tmp/c/fixtures --commit <sha>

--since <days> in place of --commit replays the first parents of HEAD of that many days, at most 500 commits.

List the laws in an agent file

The file that an agent reads first (for example AGENTS.md) can list the laws in an enforcement block. Unlike a new guardrail, this is not free for the judge: setting enforcement_file of the policy and adding .square2/architecture.json are changes that need an approval (see "Approve a weaker model"). The judge prints one [S2-POLICY] line for policy.enforcement_file and one for each value of architecture.json that it does not let pass (seven lines in all for the example below), and one digest for all of them.

  1. Add .square2/architecture.json. The schema requires every section of it; the reference lists the keys. This one loads, for a repository whose code is in src/ and whose decision structure is in .square2/decisions.md:

    {
      "schema_version": 2,
      "workspaces": [],
      "layers": [
        {
          "id": "app",
          "may_import": [],
          "why": "the application is one layer",
          "decided_by": ".square2/decisions.md#structure"
        }
      ],
      "units": [
        {
          "id": "app",
          "path": "src",
          "kind": "app",
          "layer": "app",
          "language": "js",
          "runtime": "node",
          "why": "the application",
          "decided_by": ".square2/decisions.md#structure"
        }
      ],
      "zones": [],
      "edges": {
        "source": ".square2/architecture.json",
        "forbid": [],
        "why": "no forbidden edges yet",
        "decided_by": ".square2/decisions.md#structure"
      },
      "stores": [],
      "registries": [],
      "reserved": [],
      "journeys": {
        "dir": "journeys",
        "pattern": "*.md",
        "status": "planned",
        "why": "no journeys yet",
        "decided_by": ".square2/decisions.md#structure"
      },
      "owners": [],
      "generated_marker": {
        "lines": 5,
        "patterns": [
          {
            "kind": "slash",
            "files": [
              "src/**"
            ],
            "regex": "^// generated"
          }
        ],
        "names": [],
        "exclude": [],
        "block_begin": "square2:begin",
        "block_end": "square2:end",
        "why": "generated files and blocks are marked",
        "decided_by": ".square2/decisions.md#structure"
      }
    }

    Each record shows where it comes from with why and decided_by. A record made against a defect can name, in place of decided_by or beside it, the commit of that defect: "failure_commit": "<sha>", an ancestor of HEAD. The check then needs the full history: in a shallow clone it stops with [S2-HISTORY].

  2. Set "enforcement_file": "AGENTS.md" in the policy, and add two marker lines to that tracked file: a line with block_begin and the block id enforcement, and a line with block_end and the same id. A marker line may stand inside a comment:

    <!-- square2:begin enforcement -->
    <!-- square2:end enforcement -->
  3. Add the record ARCH-SYNC (kind builtin, layer gate, with a proof) and run square2 generate. It writes the table of laws between the markers.

With ARCH-SYNC in enforce, check fails when the table is stale. In observe a stale table is one advisory line on standard error, and check still exits 0. Two things to know:

  • A block-marker line counts also inside a fenced code block. A document that shows the markers, as this page does, must go into generated_marker.exclude; otherwise ARCH-SYNC reports a block without a generator.
  • The enforcement block is plain text. A law is written into the table as it is, apart from |, which is written \|. Write a law as the sentence you want to read there.

Accept a finding

A finding of a guardrail in enforce that you cannot fix now goes to the baseline (for good, until the tree no longer has it) or into an exception (for a time). Both need an approval at the base: see "Approve a weaker model" below.

Move a finding to the baseline

  1. An approver lands a record in .square2/approvals.json on the integration branch, without a digest at first, so that baseline grow can cite it.

  2. On the branch, after updating it with the integration branch:

    node tools/square2/bin/square2.mjs baseline grow --approval <id>

    It runs the whole check and adds every new finding to .square2/baseline.json. Commit that file. square2 baseline show prints the count of each guardrail.

  3. The judge reports the new entry; the approver adds its digest to the same record (see below).

When the tree no longer has a baselined finding, check fails with [S2-BASELINE-STALE]. Run square2 baseline shrink and commit the smaller baseline; removing an entry is free.

Write an exception

Add an entry to .square2/exceptions.json on the branch:

{
  "schema_version": 2,
  "exceptions": [
    {
      "id": "debug-output",
      "guardrail": "APP-NO-CONSOLE",
      "scope": "src/debug.js",
      "reason": "the debug entry point prints to the console until the logger lands",
      "owner": "your-team",
      "adr": ".square2/decisions.md#no-console",
      "created_at": "2026-12-01",
      "expires_at": "2027-02-28"
    }
  ]
}

The scope is a path or a narrow glob; a glob of wildcards alone is refused. expires_at is at most max_exception_ttl_days after created_at. An exception covers findings of a guardrail in enforce only. After its last day it covers nothing: the finding is new again, check prints a notice, and square2 exceptions lint names it (exit 1). A new exception needs an approval; removing one is free.

Approve a weaker model

The judge reports a change that weakens the model: a lower state, a narrower scope, a removed guardrail, a grown baseline, a new exception, a changed protected file. It prints one line for each change and one digest for the whole list, and exits 1:

[S2-POLICY] guardrails.APP-NO-CONSOLE.state — Instead: keep the constraint, or get an approval at the base
policy_digest: <digest>

An entry of .square2/approvals.json with that digest, on the integration branch, admits exactly that list of changes. Its approver must be a login of approvers of the policy on the integration branch. The roles:

  • The author works on the branch of the pull request and never commits .square2/approvals.json there: two edits of the same lines of that file do not merge, and the judge then stops with [S2-JUDGE].
  • An approver lands each approval on the integration branch, in a pull request of its own, which the judge passes because an approval is free to add. Whoever can merge into the integration branch can do this; the review rule of the host on .square2/ decides who that is.

A weaker guardrail

  1. The author changes "state": "enforce" to "state": "observe" and opens the pull request. The judge job fails and prints the change and the digest.

  2. The approver lands this entry in .square2/approvals.json on the integration branch, with the digest of step 1:

    {
      "schema_version": 2,
      "approvals": [
        {
          "id": "weaken-no-console",
          "approver": "your-login",
          "date": "2026-12-01",
          "reason": "observe APP-NO-CONSOLE while the logger is introduced",
          "adr": ".square2/decisions.md#no-console",
          "policy_digest": "<digest>"
        }
      ]
    }
  3. The author updates the branch of the pull request with the integration branch (a merge or a rebase). The job judges the base commit of its event, so it sees the approval only after this update. It prints policy_approval: weaken-no-console by your-login and passes.

A grown baseline

  1. The approver lands a record without a digest (id, approver, date, reason, adr), so that baseline grow can cite it.
  2. The author updates the branch, runs square2 baseline grow --approval <id>, commits .square2/baseline.json and opens the pull request. The judge prints [S2-POLICY] baseline.<fingerprint> and the digest.
  3. The approver adds policy_digest with that digest to the same record on the integration branch.
  4. The author updates the branch again. The job prints policy_approval and passes.

A new exception

  1. The author adds the exception on the branch and opens the pull request. check passes (the finding is excepted); the judge prints [S2-POLICY] exceptions.<id> and the digest.
  2. The approver lands an entry with that digest on the integration branch.
  3. The author updates the branch. The job prints policy_approval and passes.

To see the verdict before you open the pull request, run the judge locally against the integration branch:

node tools/square2/bin/square2.mjs judge --base main

On a branch that changes the vendored copy (an upgrade, or the way back), the copy in the work tree does not match the lock of the base, and the judge stops with [S2-VENDOR]. Run the copy of the base instead, as the workflow does:

mkdir -p /tmp/square2-base
git archive main tools/square2 | tar -x -C /tmp/square2-base
node /tmp/square2-base/tools/square2/bin/square2.mjs judge --base main

Upgrade the vendored tool

  1. On a branch, vendor the new revision:

    node tools/square2/bin/square2.mjs vendor --from <path|git-url> --ref <rev>

    vendor replaces the copy at vendored_path and writes .square2/lock.json whole. It writes only what it owns: a target that holds no marker of an earlier copy is refused.

  2. Run square2 check. Copy any template that changed (tools/square2/templates/consumer/) into the repository, and keep your CONSUMER values.

  3. Open the pull request. The vendored directory and lock.json are protected files, so the judge prints one [S2-POLICY] file <path> line for each changed file and a digest; the change is judged by the copy of the base. To see this before the pull request, run the copy of the base locally (see the end of "Approve a weaker model").

  4. Approve that digest as in "Approve a weaker model", update the branch, and merge.

A new version that changes the format of the model needs two pull requests: first a tool that reads both formats, then the data in the new format. A base tool that cannot read the candidate's model stops with [S2-JUDGE].

Go back

To remove square², or to vendor an earlier copy of it, take two pull requests with green checks:

  1. Open the pull request that removes .square2/ and the vendored copy (or vendors the earlier copy). The judge reports every lost field and file, and prints a digest.

  2. An approver lands an approval of that digest on the integration branch.

  3. Update the branch with the integration branch. The branch deletes .square2/, and the approver changed .square2/approvals.json on the integration branch. So the merge stops with a modify/delete conflict on that file, or, when the file is new there, brings it back. Delete it again and commit the merge:

    git merge main
    git rm .square2/approvals.json
    git commit

    Without this update the judge cannot merge the head into the base and stops with [S2-JUDGE], exit 2. After it, the judge passes with the approval; merge the pull request.

A required check that never runs or always fails blocks every merge. Take two jobs out of the required status checks:

  • the judge job: when the pull request also deletes the judge workflow, the job stops running (for judge-pr already on that pull request);
  • the job check of square2-gate.yml: on the pull request that removes the tool it fails (its step stops with the error that the vendored tool is not in this checkout), and when the pull request also deletes the gate workflow it never reports.

Run the advisory review

The review is advisory: a model of another family than the commits' authors reads the new commits on the integration branch once a day, and its findings become issues. It never fails a job.

  1. Set the model access: see auth for the variables and the secret.
  2. Set .square2/review.json: the reviewers (a deployment of a family other than the authors'), notify, the caps, risk_paths, exclude and trailers. Describe your system in .square2/review-context.md; the reviewer reads it as context.
  3. Set the repository variable SQ2_REVIEW_ENABLED to true. A manual run of the workflow works also while it is off, and takes an explicit range (from and to).

The workflow runs three jobs: prepare writes the review context with an issues token that only reads; analyze runs square2 review guard-env and then square2 review run with the model key and no GitHub token; publish runs square2 review publish and square2 budget. The gate workflow publishes the new findings of check on the integration branch with square2 publish-gate.

The analyze job can run on a self-hosted runner: set SQ2_ANALYZE_RUNS_ON to a JSON runs-on value, for example ["self-hosted","sq2-analyze"]. Only this job runs there.