Skip to content

Store Secret Sync Metadata in Item Fields, Not 1Password Tags - #4427

Merged
ptr727 merged 4 commits into
developfrom
burndown/secrets-sync-item-fields
Nov 24, 2026
Merged

ptr727 merged 4 commits into
developfrom
burndown/secrets-sync-item-fields

Conversation

@ptr727

@ptr727 ptr727 commented Nov 24, 2026 •

Copy link
Copy Markdown
Owner

Summary

scripts/secrets_sync.py now keeps each item's sync metadata in item fields instead of 1Password tags. The file mode and the content time are the mode and mtime text fields of a sync section on the item. They are written with op item edit <id> --vault <v> sync.mode[text]=0600 sync.mtime[text]=<iso> and read back with op item get --format json. A field's section is matched by its label. That label is taken from the field's own section object, or else from the item's sections array by the section's id. The tool never reads or writes a tag now, so a push leaves an item's tags alone. Before this, every content change added another mtime: tag to the tag list that covers the whole account.

  • Where fields are read. op item list returns no fields, so a per-item op item get runs wherever the metadata decides the result: status --bucket, pull, push, and each write's read-back. status with no bucket still downloads nothing and reads no fields, and a test asserts that it makes no item get call.
  • Creating an item. A create writes the document, then its fields. If a failure or an interrupt stops the create before its fields land, the tool warns that the file has to be pushed again by name with --mode.
  • Plan wording. The plan action for a write that changes only the metadata is now fields rather than retag.
  • No tag fallback. No code path reads the old tags. An item whose metadata is still in tags has no sync.mode field, so it gets the existing refusal for a missing mode.
  • Windows behaviour is unchanged. A push keeps the existing mode field or needs --mode, and a pull ignores the field. Stub tests cover both.
  • selftest. The probes now set the sync fields, read them back, set them again and check that op document edit keeps them. Tags are no longer probed. The README and the module docstring both say the field shape has not been measured against a live op.

Closes on promotion: #4276

Owed to the maintainer: the one live cleanup run

Until the cleanup below has been run against the real account, every existing secret item stays un-migrated, and each one refuses to sync. On Linux, pull, status --bucket and push each refuse with "carries 0 sync.mode field(s)". On Windows, pull ignores the mode, so it still proceeds, using each item's update time as its content time. A Windows push of an existing item refuses until --mode is given.

Running the cleanup is a write to the 1Password account, so it is yours to start. No agent ran it, and nothing in this PR or its tests touched the real vault. The script was tried only against a stub op in a scratch directory. There, the dry run changed nothing, the first --apply migrated four constructed items, and a second --apply sent no op item edit at all.

Per the decision on #4276, the script is throwaway and is not committed to the tree. Suggested order:

  1. After this reaches the branch you run from, run python3 scripts/secrets_sync.py selftest. It measures the new field shape in a scratch vault that it creates and then deletes.
  2. Save the block below to a file outside the repository and sign in (eval "$(op signin)").
  3. Run python3 move_sync_tags.py to see the plan, then python3 move_sync_tags.py --apply. Pass --account if more than one account is configured.
  4. Delete the file.

The script handles each item as follows:

  • It looks only at Secrets <bucket> vaults. Each item carrying a mode: or mtime: tag gets one op item edit. That edit sets each sync field the item lacks and replaces the tags with the item's other tags.
  • A field that already exists is kept, because a push after this change wrote it.
  • A malformed or repeated tag is dropped without a field, and the script names that item so it can be pushed again by name with --mode.
  • After each edit it reads the item back and stops if a tag remains or a field is missing.

Two things are unmeasured. One is whether --tags "" clears every tag on a live op. The other is the field shape itself. The read-back is what catches a difference.

#!/usr/bin/env python3
"""Move each secret item's `mode:` and `mtime:` tags into its `sync` fields, then strip the tags.

Throwaway, for issue #4276: run once, then delete. It is not part of the repository's tooling.
It reads every `Secrets <bucket>` vault through an ambient `op` session, so sign in first.
Without `--apply` it prints what it would do and writes nothing.

Per item carrying a `mode:` or `mtime:` tag, one `op item edit` sets each missing field and
replaces the tags with the item's other tags. A field that already exists is kept, since a push
since the upgrade wrote it. A tag whose value is malformed or repeated is dropped without a
field, and the item is named, so it is pushed again by name with `--mode`. A second run finds no
such tag and writes nothing.
"""

from __future__ import annotations

import argparse
import datetime
import json
import re
import subprocess
import sys

VAULT = re.compile(r"Secrets [a-z0-9-]+")
MODE = re.compile(r"[0-7]{3,4}")
PREFIXES = {"mode": "mode:", "mtime": "mtime:"}


class Failed(Exception):
    pass


def op(binary: str, account: str | None, *args: str) -> bytes:
    argv = [binary, *args, *(["--account", account] if account else [])]
    done = subprocess.run(argv, capture_output=True, check=False)
    if done.returncode != 0:
        detail = done.stderr.decode("utf-8", "replace").strip()[:500]
        raise Failed(f"op {' '.join(args[:2])} failed rc={done.returncode}: {detail}")
    return done.stdout


def op_json(binary: str, account: str | None, *args: str) -> object:
    return json.loads(op(binary, account, *args, "--format", "json").decode("utf-8"))


def valid(label: str, value: str) -> bool:
    if label == "mode":
        return bool(MODE.fullmatch(value)) and int(value, 8) <= 0o777
    try:
        moment = datetime.datetime.fromisoformat(value)
    except ValueError:
        return False
    return moment.tzinfo is not None


def sync_labels(item: object) -> set[str]:
    assert isinstance(item, dict), "op item get returned JSON that is not an object"
    named = {s.get("id"): s.get("label") for s in item.get("sections", []) or []}
    labels: set[str] = set()
    for field in item.get("fields", []):
        section = field.get("section")
        if (
            isinstance(section, dict)
            and section.get("label", named.get(section.get("id"))) == "sync"
        ):
            labels.add(str(field.get("label")))
    return labels


def plan_item(
    binary: str, account: str | None, vault: str, row: dict[str, object]
) -> list[str] | None:
    """The `op item edit` arguments for one item, or None where it carries no such tag."""
    tags = [str(t) for t in row.get("tags", []) or []]
    moved = [t for t in tags if t.startswith(tuple(PREFIXES.values()))]
    if not moved:
        return None
    have = sync_labels(op_json(binary, account, "item", "get", str(row["id"]), "--vault", vault))
    assignments: list[str] = []
    for label, prefix in PREFIXES.items():
        values = [t[len(prefix) :] for t in moved if t.startswith(prefix)]
        if label in have or not values:
            continue
        if len(values) == 1 and valid(label, values[0]):
            assignments.append(f"sync.{label}[text]={values[0]}")
        else:
            print(
                f"  note: {row['title']}: {len(values)} {prefix} tag(s) not valid, dropped without a field"
            )
    kept = [t for t in tags if t not in moved]
    return ["--tags", ",".join(kept), *assignments]


def check(
    binary: str, account: str | None, vault: str, item_id: str, assignments: list[str]
) -> None:
    item = op_json(binary, account, "item", "get", item_id, "--vault", vault)
    assert isinstance(item, dict)
    left = [t for t in item.get("tags", []) or [] if str(t).startswith(tuple(PREFIXES.values()))]
    want = {a.split(".", 1)[1].split("[", 1)[0] for a in assignments if a.startswith("sync.")}
    missing = want - sync_labels(item)
    if left or missing:
        raise Failed(f"item {item_id} still carries {left} or lacks sync fields {sorted(missing)}")


def main() -> int:
    ap = argparse.ArgumentParser(description=(__doc__ or "").splitlines()[0])
    ap.add_argument("--apply", action="store_true", help="write the changes, default prints them")
    ap.add_argument("--account", help="the op account, where more than one is configured")
    ap.add_argument("--op", default="op", help="the op executable, default op on PATH")
    a = ap.parse_args()
    vaults = op_json(a.op, a.account, "vault", "list")
    assert isinstance(vaults, list), "op vault list returned JSON that is not an array"
    changed = 0
    for vault in sorted(vaults, key=lambda v: str(v["name"])):
        if not VAULT.fullmatch(str(vault["name"])):
            continue
        vid = str(vault["id"])
        rows = op_json(a.op, a.account, "item", "list", "--vault", vid, "--categories", "Document")
        assert isinstance(rows, list), "op item list returned JSON that is not an array"
        for row in sorted(rows, key=lambda r: str(r["title"])):
            edit = plan_item(a.op, a.account, vid, row)
            if edit is None:
                continue
            changed += 1
            fields = edit[2:]
            print(
                f"{vault['name']}: {row['title']}  tags -> [{edit[1]}]  set {fields or 'no field'}"
            )
            if a.apply:
                op(a.op, a.account, "item", "edit", str(row["id"]), "--vault", vid, *edit)
                check(a.op, a.account, vid, str(row["id"]), fields)
    verb = "Moved" if a.apply else "Would move"
    print(
        f"{verb} the tags of {changed} item(s).{'' if a.apply or not changed else ' Pass --apply to write.'}"
    )
    return 0


if __name__ == "__main__":
    try:
        sys.exit(main())
    except Failed as exc:
        print(f"failed: {exc}", file=sys.stderr)
        sys.exit(2)
    except KeyboardInterrupt:
        print("interrupted", file=sys.stderr)
        sys.exit(130)

Verification

  • python3 tests/test_secrets_sync.py: 170 tests, OK. This covers the new fake op item get and op item edit assignments. New cases cover a create writing its fields after the document, every way a create can stop before its fields land, an item carrying only tags being refused by pull, status --bucket and push, a field whose section carries only its id, unexpected op item get shapes failing loudly, and selftest reporting fields that repeat rather than replace.
  • python3 -m unittest discover -s tests -p test_restore_secrets.py: OK.
  • ruff format and ruff check (the CI pins), mypy, and the prose gate are clean on the changed files.

Local review

Three local strict review passes were recorded, the last over the pushed head with no findings. Earlier passes raised four findings, all fixed in this branch: the create path's recovery warning missed the listing and then the create call itself, an over-hardening id check, and duplicated op argument lists in selftest.

🤖 Generated with Claude Code

ptr727 and others added 3 commits November 24, 2026 04:38
secrets_sync.py now reads and writes each item's mode and content time as
the mode and mtime text fields of a sync section on the item, through op
item edit assignments and op item get. It never reads or writes a tag, so a
push leaves an item's tags as they are and the account's tag list stops
growing with every content change.

The listing carries no fields, so a per-item op item get runs wherever the
metadata decides the outcome: status --bucket, pull, push, and the read
back. status with no bucket reads no item's fields. A create writes the
document, then its fields, and warns with the --mode recovery where the
field write fails. The plan action for a metadata-only write is now
"fields". selftest measures the sync fields instead of the tags, and the
field shape stays unmeasured against a live op.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
… Lists

A create that stopped between the document and its fields, at the listing
that finds the new item's id or on an interrupt, left the item without its
sync fields and printed no recovery. The warning now covers that listing as
well as the field write, with a test for each way the create can stop.

The op item get and op item edit argument lists are built once and shared
with selftest, so selftest measures the exact calls push and pull send, and
selftest no longer reads the same item twice. The check that op item get
returns the requested id is removed, since that output is the account's
own read back by explicit id.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
A document create that reported a failure the read-back could not confirm,
or that an interrupt stopped, may still have landed with no sync fields.
The --mode recovery warning now covers the create call too, with a test
for each case.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Copilot AI lite review requested due to automatic review settings November 24, 2026 12:48
@ptr727

ptr727 commented Nov 24, 2026

Copy link
Copy Markdown
Owner Author

A recorded local strict-review pass covers head 8c8a42e100276e0c77f1c619c3eef653a400b2d4, the content this pull request carries at that commit against develop, and it recorded 0 findings.

@coderabbitai

coderabbitai Bot commented Nov 24, 2026 •

Copy link
Copy Markdown

Explain Change →

Important

Review skipped

Auto reviews are disabled on this repository. Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

Run configuration

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Use the checkbox below for a quick retry:

  • Trigger review
Finishing Touches

Generate unit tests (beta)

  • Commit to this branch
  • Create a new PR
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

Share

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

A critical active finding shows section resolution skips all sync fields for the documented item JSON shape, breaking pull, status, and push until the lookup and fixture are corrected.

1 open issue
What changed in this PR

Moves secret synchronization metadata from account-wide 1Password tags into per-item sync.mode and sync.mtime fields while preserving user-defined tags.

Changes:

  • Reads and writes metadata through op item get and op item edit.
  • Updates create, push, pull, status, recovery, and self-test behavior.
  • Expands tests and documentation for field-based metadata and migration.
File Description
tests/​test_secrets_sync.py Updates the fake op implementation and regression coverage for field-based synchronization metadata, recovery, validation, tags, and self-test behavior.
scripts/​secrets_sync.py Implements storage, reading, validation, recovery, and verification of synchronization metadata in item fields.
scripts/​README.md Documents the sync field format, field-based workflows, recovery behavior, migration implications, and self-test expectations.

Review effort: Lite

Comment thread scripts/secrets_sync.py Resolved
@codecov

codecov Bot commented Nov 24, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 79.62%. Comparing base (b38e084) to head (50ff182).
⚠️ Report is 343 commits behind head on develop.

Additional details and impacted files
@@             Coverage Diff             @@
##           develop    #4427      +/-   ##
===========================================
- Coverage    81.60%   79.62%   -1.99%     
===========================================
  Files           26       47      +21     
  Lines         9070    16398    +7328     
===========================================
+ Hits          7402    13057    +5655     
- Misses        1668     3341    +1673     
Flag Coverage Δ
python-3.13 79.62% <100.00%> (-1.99%) ⬇️

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@ptr727

ptr727 commented Nov 24, 2026

Copy link
Copy Markdown
Owner Author

@coderabbitai review

@ptr727

ptr727 commented Nov 24, 2026

Copy link
Copy Markdown
Owner Author

/review

@coderabbitai

coderabbitai Bot commented Nov 24, 2026 •

Copy link
Copy Markdown
Action not completed

Head commit changed.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

The op item get field shape is unmeasured, and a field's section object may
carry only its id, with the label in the item's top-level sections array.
Reading the label from the field alone would then find no sync field on any
item, and every pull and push would refuse. The label is now read from the
field's section object, or else by that object's id from the sections
array, with a test of the id-only shape.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@ptr727

ptr727 commented Nov 24, 2026

Copy link
Copy Markdown
Owner Author

A recorded local strict-review pass covers head 50ff182070b53cbc4cc4f4e36f03c44b7bb2c534, the content this pull request carries at that commit against develop, and it recorded 0 findings.

@ptr727
ptr727 merged commit 5e71f88 into develop Nov 24, 2026
14 checks passed
@ptr727
ptr727 deleted the burndown/secrets-sync-item-fields branch November 24, 2026 13:25
ptr727 added a commit that referenced this pull request Nov 24, 2026
…lts, Secret Sync Fields, and Audit Account Fixes (#4428)

Promotes the 28 pull requests that landed on develop since the last
promotion (#4388), from the away-mode backlog burndown run.

- #4391: Drop the false XML comment suppression claim from the .NET
conventions.
- #4390: Blank quotations after a heredoc label on its opening line in
the paste-safe rule.
- #4392: Carry attention lists, cut lists, and opt-in billing in the
`backlog_metrics.py` JSON.
- #4393: Gate `configure.sh apply`'s interaction limit on a committed
bot verification record.
- #4394: Make the gh and node report note say a one-line vendor source
is configured.
- #4395: Add ShellCheck and shfmt lint tasks to the VS Code task
snippets.
- #4396: Count a CodeRabbit clean pass on the head in the digest's
`other_reviewed`.
- #4401: Date the line-ending intentRefs by the skill and trim advisory
restatements.
- #4399: Share one any-level heading region primitive between
`heading_body` and `extract_anchored`.
- #4398: Name the hub pull requests a standup lands through, and add
HACS first-run guidance.
- #4404: Add a PowerShell section to CODESTYLE.md and narrow the shell
rule.
- #4405: Close AUDIT.md section 10's convergence loop and fix three
skill pointers.
- #4409: Route CODESTYLE.md's General section to the language skills
(part of #1153, which stays open).
- #4410: Detect a C# test project by its own text rather than its file
name.
- #4411: Drop the unruled "working gate is not drift" sentence from
CODESTYLE.md.
- #4412: Track the newest upstream line of each pinned host tool.
- #4413: Correct AUDIT.md section 0's account of what the audit checks.
- #4416: Add a required coverage shield class to the README audit.
- #4414: Tie drive-pr's merge to its authorization and align the pass
moments.
- #4417: Pass over a second SIGTERM in `pr_review.py` so an interrupt
prints one line.
- #4418: Point the report-path placeholder at AUDIT.md section 8.
- #4419: Correct the audit account copies outside AUDIT.md section 0.
- #4422: Drop the archived DevKitCIoT from the rollout checklists.
- #4423: Report a stale `pullRequestCheck: false` and correct AUDIT.md
section 6.
- #4424: Add a `prune` subcommand to retire orphaned canonical review
passes.
- #4425: Drop the archived DevKitCIoT from the reusable-workflows
checklists and fix a normalization docstring.
- #4427: Store secret sync metadata in item fields, not 1Password tags.
- #4426: Declare and apply the Actions workflow token defaults through
`configure.sh` (the `configure.sh` part of #1783, which stays open).

## Owed by the maintainer

- #4412: A live run of the new host-tool line tracker. Scheduled runs
start only once this reaches `main`, and a `workflow_dispatch` would
prove it sooner.
- #4426: A fleet `configure.sh apply` for the workflow token defaults,
after the per-repository read the 2026-11-01 answer requires. Please
also confirm the new `--lower-workflow-token` option, which a `write`
repository needs for the apply to lower its default.
- #4427: Run `python3 scripts/secrets_sync.py selftest`, then the
cleanup script in that pull request's body (`move_sync_tags.py`, dry run
first, then `--apply`). Until that runs, every un-migrated secret item
refuses to sync.
- #4393: The pilot's first interaction limit is set by hand in its
settings and its bots verified there. The verification record is
committed afterwards through a hub pull request, and only then does
`apply` set the limit fleet-wide.
- A fleet resync is owed, because carried text changed: AGENTS.md,
GOVERNANCE.md, CODESTYLE.md, and several skills.

Fixes #4387
Fixes #4383
Fixes #4284
Fixes #1095
Fixes #4299
Fixes #4370
Fixes #4364
Fixes #4173
Fixes #4064
Fixes #3536
Fixes #3929
Fixes #3808
Fixes #3812
Fixes #3810
Fixes #4320
Fixes #4232
Fixes #1748
Fixes #1607
Fixes #1270
Fixes #1170
Fixes #3692
Fixes #4415
Fixes #3908
Fixes #1648
Fixes #4276

🤖 Generated with [Claude Code](https://claude.com/claude-code)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants