Automation-first Python library for local file / directory / zip operations, HTTP downloads, and remote storage (Google Drive, S3, Azure Blob, Dropbox, SFTP). Actions are defined as JSON and dispatched through a central registry so they can be executed in-process, from disk, over a TCP socket, or over HTTP.
Layered architecture with Facade + Registry + Command + Strategy patterns:
automation_file/
├── __init__.py # Public API facade (__all__); launch_ui is loaded lazily via __getattr__
├── __main__.py # CLI entry: subcommands plus the legacy -e/-d/-c/--execute_str flags
├── cli_storage.py # the `storage` subcommand (ls, cp, mv, rm, sync, checksum, ...)
├── cli_operations.py # the `integrity`, `pipeline` and `audit` subcommands
├── cli_common.py # what the subcommands share: JSON output, --init, --audit, the cli actor
├── exceptions.py # FileAutomationException hierarchy
├── logging_config.py # file_automation_logger (file + stderr handlers)
├── core/ # Engine: action_registry (ActionRegistry, build_default_registry), action_executor
│ # (shared `executor`), callback_executor, package_loader, plugins, dag_executor,
│ # action_queue, json_store, substitution; cross-cutting helpers: retry, quota,
│ # rate_limit, circuit_breaker, file_lock, sqlite_lock, checksum, manifest, crypto,
│ # secrets, config, config_watcher, audit, metrics, tracing, progress, fim, content_store
├── local/ # Strategy modules: file/dir/zip/tar/archive ops, sync, diff, text/JSON/data edits,
│ # templates, versioning, trash, shell_ops (argv-only subprocess), conditional;
│ # safe_paths.py guards against path traversal
├── remote/ # url_validator (SSRF guard), http_download, cross_backend, fsspec_bridge, and one
│ # subpackage per backend: google_drive, s3, azure_blob, dropbox_api, sftp, ftp,
│ # onedrive, box (client.py + *_ops.py + register_<backend>_ops); smb and webdav
│ # have a client only
├── storage/ # Universal storage layer: uri (StorageURI), types (FileInfo, Checksum,
│ # StorageCapabilities), backend (StorageBackend contract), local_storage,
│ # memory_storage, object_storage (ObjectStorage), s3_storage, azure_storage,
│ # session_storage (SessionStorage), sftp_storage, ftp_storage, gdrive_storage,
│ # onedrive_storage, dropbox_storage, webdav_storage, smb_storage, fsspec_storage,
│ # resolver (StorageResolver), file (File), storage (Storage), streams,
│ # tree (copy_tree, sync_tree),
│ # actions (FA_storage_* and register_storage_ops)
├── events/ # Event model: model (Event, Severity, the ten core events), bus (EventBus,
│ # event_bus, emit), context (correlation_scope, actor_scope), storage_bridge
├── integrity/ # IntegrityMonitor 2.0: target, hashing, snapshot, manifest (schema 2), baseline,
│ # detector, report, alerts, remediation, watcher / local_watcher, legacy, monitor,
│ # actions (FA_integrity_*); core/fim.py re-exports IntegrityMonitor
├── server/ # tcp_server, http_server, mcp_server (MCP over stdio), mcp_policy (MCPPolicy),
│ # mcp_tools + mcp_*_tools (the fourteen semantic tools), web_ui, metrics_server,
│ # action_acl (ActionACL), network_guards (ensure_loopback)
├── client/ # HTTPActionClient for the HTTP action server
├── pipeline/ # Pipeline runtime: model (Task, RetryPolicy, PipelineRun, ...), graph, pipeline
│ # (Pipeline), runner + worker, substitution, store (RunStore, MemoryRunStore,
│ # SQLiteRunStore), definition (YAML/JSON + PIPELINE_SCHEMA), reporting, actions
├── app/ # Application layer (no Qt, no SDK at import): services (AppServices), one
│ # *_service per navigation entry, pipeline_draft (PipelineDraft), masking
├── audit/ # Audit schema v2: record (AuditRecord), store (AuditStore, AuditQuery,
│ # MemoryAuditStore), sqlite_store (SQLiteAuditStore), trail (AuditTrail,
│ # audit_trail, configure_audit), actions (FA_audit_*)
├── trigger/, scheduler/, notify/ # watchdog file triggers, the scheduler (cron with a time zone,
│ # manual, file, event and pipeline triggers; run records),
│ # notification sinks;
│ # notify/router.py routes events to sinks (NotificationRouter);
│ # each registers its own FA_* ops
├── project/ # ProjectBuilder, create_project_dir
├── ui/ # PySide6 GUI on the application layer: launcher.launch_ui, main_window.MainWindow
│ # (sidebar), pages/ (one per navigation entry, pipeline_canvas, task_form, run_panel,
│ # advanced_page), worker.ActionWorker, log_widget.LogPanel, tabs/ (the older tabs,
│ # shown under Advanced)
└── utils/ # file discovery, fast find, grep, duplicate finder, backup rotation
architecture.md §2 carries the same map with one row per directory; keep the two in step.
Key design patterns in use:
- Facade:
automation_file/__init__.pyre-exports every supported name (execute_action,driver_instance,start_autocontrol_socket_server, …). - Registry + Command:
ActionRegistrymaps action name → callable. JSON action lists are command objects ([name, kwargs]/[name, [args]]/[name]) dispatched through the registry. - Template Method:
ActionExecutor._execute_eventdefines the single-action lifecycle (resolve → call → wrap result);execute_actionis the outer iteration template. - Strategy: Each
local/*_ops.pyandremote/<backend>/*_ops.pymodule is an independent strategy that plugs into the registry. - Singleton (module-level):
driver_instance,executor,callback_executor,package_managerare shared instances wired in__init__.pysocallback_executor.registry is executor.registry. - Builder:
ProjectBuilderassembles thekeyword/+executor/skeleton.
ActionRegistry— mutable name → callable mapping.register,register_many,resolve,unregister,event_dict(live view for legacy callers).ActionExecutor— holds a registry and runs JSON action lists.execute_action(list|dict, validate_first=False, dry_run=False),execute_action_parallel(list, max_workers=None),validate(list) -> list[str],execute_files(paths),add_command_to_executor(mapping).CallbackExecutor— runs a registered trigger, then a user callback, sharing the executor's registry.PackageLoader— imports a package by name and registers its top-level functions / classes / builtins as<package>_<member>.GoogleDriveClient— wraps OAuth2 credential loading; exposesservicelazily.later_init(token_path, credentials_path)bootstraps;require_service()raises if not initialised.S3Client/AzureBlobClient/DropboxClient/SFTPClient— singleton wrappers around the SDKs of their extras. Each exposeslater_init(...)plusclose()where relevant. Their ops are auto-registered bybuild_default_registry();register_<backend>_ops(registry)is still exported so callers can populate custom registries.MainWindow— PySide6 window with a sidebar (ui/main_window.py): Dashboard, Files, Storage, Pipelines (a canvas editor overPipelineDraft), Scheduler, Integrity, Audit, Notifications, Settings, and Advanced, which holds the older tabs (Local, Transfer, Progress, JSON actions, Triggers, Servers). Each page talks only to its service inautomation_file.app; long work runs throughActionWorker(QRunnable)on the globalQThreadPool. A new screen starts as a service inapp/, tested without Qt, and a page is a thin view of it. The Web UI (server/web_ui.py) renders the same services, read-only.launch_ui(argv=None)— boots / reuses aQApplication, showsMainWindow, and returns the exec code. Exposed lazily on the facade via__getattr__so the Qt runtime isn't paid for by non-UI importers.TCPActionServer— threaded TCP server that deserialises a JSON action list per connection. Defaults to loopback; optionalshared_secretenforcesAUTH <secret>\nprefix.HTTPActionServer—ThreadingHTTPServerexposingPOST /actionsplusGET /healthz,/readyz,/openapi.jsonand/progress. Defaults to loopback; optionalshared_secretenforcesAuthorization: Bearer <secret>.Quota— frozen dataclass capping bytes and wall-clock seconds per action or block (check_size,time_budgetcontext manager,wrapsdecorator).0disables each cap.retry_on_transient(max_attempts, backoff_base, backoff_cap, retriable)— decorator that retries with capped exponential back-off and raisesRetryExhaustedExceptionchained to the last error.safe_join(root, user_path)/is_within(root, path)— path traversal guard;safe_joinraisesPathTraversalExceptionwhen the resolved path escapesroot.File(uri)/Storage(uri)— the universal storage layer's application API: one file, one directory, in any backend. Both resolve their backend on every call throughStorageResolver(Storage.mount,Storage.register_scheme).StorageBackend— the contract a storage backend implements. The public operations (exists,stat,list_dir,mkdir,upload,download,delete,checksum,read_bytes,write_bytes,copy_from,move_from) are template methods; a backend supplies only the_-prefixed primitives. Twelve are built in:LocalStorage,MemoryStorage,S3StorageandAzureStorage(both onObjectStorage),SFTPStorageandFTPStorage(both onSessionStorage),GoogleDriveStorage,OneDriveStorage,DropboxStorage, and the mountedWebDAVStorage,SMBStorageandFsspecStorage. Each uses its backend's shared client singleton unless given one, and reports a missing SDK with the extra to install.IntegrityMonitor— compares a tree at any storage URI with an approved baseline (create_baseline,verify,accept,watch,start/stop,snapshot) and returns aDriftReport; drift is published as oneIntegrityViolationper pass. It only reads unless aRemediationPolicyis passed. Its options are keyword arguments (MonitorKeywords). The first monitor's call andcheck_once()summary are kept, including the notification throughmanageror the process-widenotification_manager.Pipeline— tasks (a callable taking aTaskContext, or anFA_*action) withdepends_on, run in dependency order withRetryPolicy, a timeout,whenconditions and idempotency keys.runexecutes in the calling thread,startin the background,resume(run_id)repeats only what did not succeed,run(dry_run=True)plans. Every transition is checkpointed in aRunStore(MemoryRunStore,SQLiteRunStore) and reported as apipeline.*/task.*event. A task fails only by raising: an action that reports through its return value needs its raising form (FA_storage_verifywithstrict=True).Scheduler/scheduler— runs an action list or a pipeline when one of its triggers fires (CronTriggerwith an IANA time zone, a manualrun_now,FileTrigger,EventTrigger,PipelineTrigger). Every firing is aJobRunwith one of seven states (scheduled,started,completed,failed,skipped,timeout,cancelled) in a bounded history. Overlap is refused unlessallow_overlap=True. A failed or timed-out run publishes onescheduler.error. Tests drive it withtick(now)and an injected clock; never sleep through a minute.Scheduler.add(name, cron, action_list, *, allow_overlap=False)and the four originalFA_schedule_*actions keep their shape.NotificationRouter/Route/notification_router— delivers events to named sinks by type, source and minimum severity, with deduplication and a rate limit per route and sink. Opt-in: nothing is routed until a route exists and the router is started (FA_notify_route_addandAutomationConfig.apply_to(manager, router)start it). While it is active,notify_on_failureand the integrity monitor leave the direct notification to it, so nothing is announced twice.AuditTrail/audit_trail/configure_audit(path)— audit schema v2: oneAuditRecordper event and per storage operation in anAuditStore(SQLiteAuditStore,MemoryAuditStore), searched withaudit_search/FA_audit_search. Records nothing until configured, and never raises into the code it audits. The v1AuditLogis unchanged.Event/EventBus/event_bus— every component reports through events (PipelineFailed,TaskFailed,IntegrityViolation,StorageError, ...) with a severity, a correlation ID and an actor; consumers subscribe on the bus by class, type name or prefix. New code that has something to report publishes an event; it does not call a notification sink or the audit log directly.StorageURI/parse_storage_uri—<scheme>://<authority>/<path>;FileInfo,Checksum,StorageCapabilitiesare the frozen value types the layer returns.
mainbranch: stable releases, publishesautomation_fileto PyPI (version instable.toml).devbranch: development, publishesautomation_file_devto PyPI from CI. The version indev.tomlis only a floor.- Keep
dependenciesand[project.optional-dependencies](dev) in sync across both TOMLs;tests/test_dev_toml_parity.pyfails when those, the entry points,requires-python,[build-system]or[tool.setuptools]differ. The basedependenciescarry no cloud SDK and no GUI toolkit: each backend's SDK,pyarrowandPySide6live in an extra (s3,azure,gdrive,dropbox,sftp,smb,fsspec,onedrive,box,parquet,gui;ftpandwebdavare empty;alllists every one). Do not move one intodependencies, and do not import one at module level: code asks for it at the moment of use withautomation_file.core.optional.require_module(name, extra=...), which raisesOptionalDependencyExceptionnaming the extra.tests/test_optional_dependencies.pyfails when the package cannot be imported without them, when importing it loads one, or when the extras andalldrift apart. A new optional package needs its extra in both TOMLs, its line inall, and its entry incore.optional.EXTRAS. - Patch releases bump themselves. The publish workflow runs
scripts/stable_release.py bump, which raises the patch in bothstable.tomlanddev.toml, then builds, uploads to PyPI and commits the bump back tomaintagged asvX.Y.Z. Do not hand-bump the patch before merging tomain. The next publish run is skipped via a commit-message guard (chore: bump version), so the bump itself never re-triggers publishing. The dev channel takes its number from PyPI, so never hand-bumpdev.tomlfor a patch either. - A MINOR or MAJOR release is written in the pull request. Set the version to
X.Y.0in bothstable.tomlanddev.tomlin the pull request that goes tomain. When a file'sMAJOR.MINORis above the newestvX.Y.Ztag's, the script publishes the version as written instead of adding a patch; it stops the job when the stable version would not be above the newest tag. What counts as MINOR and MAJOR is indocs/source/Eng/usage/api_policy.rst. - CI: GitHub Actions — a
lintjob on Ubuntu (Python 3.12), thenpyteston Windows across Python 3.11 / 3.12 / 3.13 / 3.14. One workflow per branch:.github/workflows/ci-dev.yml,.github/workflows/ci-stable.yml. - CI steps:
lint(ruff check + ruff format --check + mypy) →pytestwith coverage, installed with.[all,test]→ uploadscoverage.xmlas an artifact. Two more jobs followlint:minimalinstalls.[test]only and runs the whole suite (the tests of a missing extra skip), andextrasinstalls each extra on its own.publish-devneeds all four. Apackagejob builds the sdist and the wheel and runstwine check; it gates nothing..github/workflows/integration.yml(§ Testing) runs next to them and gates nothing either. - Stable publishing lives in a separate workflow (
.github/workflows/publish.yml) that runs on push tomain: picks the version in both TOMLs (scripts/stable_release.py), copiesstable.tomltopyproject.toml, builds the sdist + wheel,twine uploadviaPYPI_API_TOKEN, then commits + tags + pushes and createsgh release create v<version> --generate-notes. - Dev publishing is the
publish-devjob at the end ofci-dev.yml. It runs only on a push todev, afterlintandpytestpass:scripts/dev_release.py preparewritespyproject.tomlfromdev.tomlwith one patch above the newestautomation_file_devon PyPI, the job builds and runstwine check, and it uploads (samePYPI_API_TOKEN) only when the commit is still the tip ofdevand the wheel differs from the newest published one. Nothing is committed back. - Both publish jobs hold
PYPI_API_TOKEN, so they install their tools (build,twine, and the build backendsetuptools) with one command and nothing else:python -m pip install --require-hashes --only-binary :all: -r .github/requirements/publish.txt. Nopip install --upgrade pip, no unpinned install;tests/test_workflow_actions.pyfails on any otherpip installin a job that is given the token. To add or raise a tool, edit.github/requirements/publish.inand regeneratepublish.txtwith theuv pip compilecommand written in that file. Dependabot reads the directory and proposes updates ondev. - Both publish jobs build with
python -m build --no-isolation, so the backend is the lockedsetuptoolsand nothing is downloaded at build time.--no-isolationchecks[build-system] requiresagainst what is installed instead of installing it: when you raise that floor instable.tomlanddev.toml, or add a build requirement, regeneratepublish.txtin the same commit.tests/test_workflow_actions.pyfails on a build without--no-isolationin those jobs and on a build requirement the lock does not satisfy. pre-commitis configured (.pre-commit-config.yaml): trailing-whitespace, eof-fixer, check-yaml, check-toml, check-added-large-files, ruff, ruff-format, mypy. Install withpre-commit installafter cloning.
python -m pip install -r dev_requirements.txt pytest pytest-cov
python -m pip install -e ".[all,dev]" # every backend and the GUI, plus ruff, mypy, pre-commit
python -m pytest tests/ -v --tb=short
ruff check automation_file/ tests/
ruff format --check automation_file/ tests/
mypy automation_file/
python -m automation_file --helpTesting:
- Unit tests live under
tests/(pytest). Fixtures intests/conftest.py(sample_file,sample_dir). - Tests cover every module in
core/,local/,remote/url_validator,project/,server/,utils/, plus a facade smoke test, retry/quota/safe_paths, HTTP+TCP auth, and optional-backend registration. - Google Drive / HTTP-download / S3 / Azure / Dropbox / SFTP code paths that require real credentials or network access are not exercised in CI — only their URL-validation, auth, and guard-clause behaviour are.
tests/integration/runs the storage contract suite against real services (S3Mock, Azurite, OpenSSH, FTP, WebDAV, Samba). Each module is skipped unless itsFA_IT_*variables are set;tests/integration/start_service.sh <service>starts the container and exports them, and.github/workflows/integration.ymlruns one service per job withFA_IT_REQUIRED=1, which turns a skip into a failure. The same workflow runs the unit tests on Linux and macOS. It does not gate publishing. A backend whose service can run in a container gets a module there, an entry in the script and one in the workflow matrix.- Run all tests before submitting changes:
python -m pytest tests/ -v.
- Python 3.11+ — use
X | Yunion syntax, notUnion[X, Y]. - Use
from __future__ import annotationsat the top of every module for deferred type evaluation. - Exception hierarchy: all custom exceptions inherit from
FileAutomationException; neverraise Exception(...)directly. - Logging: use
file_automation_loggerfromautomation_file.logging_config. Neverprint()for diagnostics. - Action-list shape:
[name],[name, {kwargs}], or[name, [args]]— nothing else. - Delete all unused code — no dead imports, commented-out blocks, unreachable branches, or
_old_-prefixed names. Git history is the archive. - Prefer updating the registry over extending the executor class. Plugins register via
add_command_to_executor({name: callable}). - Public API: what
docs/source/Eng/usage/api_policy.rstlists (the facade and package__all__s,FA_*actions with their parameters and result shapes, CLI flags and exit codes, storage URI syntax, versioned data formats, event types and payload keys, the exception hierarchy). Never rename, remove or change the meaning of one of those in place. Retire it withautomation_file.core.deprecation.deprecated(since=, removal=, replacement=)orwarn_deprecated, keep it working for at least two minor releases, and remove it only in a major release. A format written to disk carries a schema version, and its reader refuses a version it does not know.
All code must follow secure-by-default principles. Review every change against the checklist below.
- Never use
eval(),exec(), orpickle.loads()on untrusted data. - Never use
subprocess.Popen(..., shell=True)— always pass argument lists. - Never log or display secrets, tokens, passwords, or API keys. OAuth2 tokens handled by
GoogleDriveClientare kept on disk only at the caller-suppliedtoken_path. - Use
json.loads()/json.dumps()for serialisation — never pickle. - Validate all user input at system boundaries (CLI args, URL inputs, TCP payloads).
- All outbound HTTP requests to user-specified URLs must validate the target first via
automation_file.remote.url_validator.validate_http_url:- Only
http://andhttps://schemes — rejectsfile://,ftp://,data:,gopher://. - Resolve the hostname and reject IPs in private / loopback / link-local / reserved / multicast / unspecified ranges.
- Only
http_download.download_filecalls the validator, usesallow_redirects=False, enforces a default 20 MB response cap and 15 s connection timeout, and never downgrades TLS verification.- Never pass user-supplied URLs directly to
urlopen()/requests.*without the validator.
- All HTTPS requests must use default TLS verification — never set
verify=False. - No bespoke SSH logic in this project; if added, match PyBreeze's
InteractiveHostKeyPolicypattern.
- This library does not spawn subprocesses on the hot path. If you add one, pass argument lists (never
shell=True), set an explicittimeout, and never interpolate user input into a command string.
TCPActionServerbinds tolocalhostby default.start_autocontrol_socket_server(host=…)raisesValueErrorif the resolved address is not loopback unlessallow_non_loopback=Trueis passed explicitly.- Do not remove the loopback guard to "make it easier to test remotely". The server dispatches arbitrary registry commands; exposing it to the network is equivalent to exposing a Python REPL.
- The server accepts a single JSON payload per connection (
recv(8192)). Do not raise that limit without also adding a length-framed protocol. quit_servertriggers an orderly shutdown; do not add an administrative bypass that skips the loopback check.ActionACLchecks every registered action name anywhere in a request, so an action nested in the arguments of another (FA_execute_action, a pipeline definition, a scheduled list) is covered; the MCP server applies the same check against the tools it exposes (nested_action_names). Neither can see what a request only points to: an action file, a definition file, a stored pipeline run. A new action that runs other actions from such a place must say so in its documentation, and must never be added to a default allow list.- Optional
shared_secret=enforces anAUTH <secret>\nprefix; the comparison useshmac.compare_digest(constant time). Never log the secret or the raw payload.
HTTPActionServer/start_http_action_servermirror the TCP server's posture: loopback-only by default,allow_non_loopback=Truerequired to bind elsewhere, optionalshared_secretenforced asAuthorization: Bearer <secret>usinghmac.compare_digest.POST /actionsis the only endpoint that runs anything; theGETroutes (/healthz,/readyz,/openapi.json,/progress) only report. Request body capped at 1 MB — do not raise without also switching to a streaming parser.- Responses are JSON. Auth failures return
401; malformed JSON returns400; unknown paths return404.
- The semantic tools work only below the roots of the server's
MCPPolicy, and with no root they refuse. A local root is enforced byLocalStorage(root)/safe_join, never by comparing strings; a remote root by scheme, exact authority and a path prefix that ends at a segment boundary. - The default policy is read-only. Writing, overwriting and deleting are three separate permissions; never fold one into another, and never make a new changing tool available without
dry_run. - A pipeline made or run through MCP uses the guarded action set of
mcp_pipeline_actions.py. An action added with--pipeline-actionsruns unconfined, and the manual says so: keep it that explicit. - A refused call is logged without argument values, and returned as a tool result with
isError.
- Any caller resolving a user-supplied path against a trusted root must go through
automation_file.local.safe_paths.safe_join(raisesPathTraversalException) or theis_withincheck. Never concatenate +Path.resolve()yourself and skip the containment check — symlinks and..segments bypass naive string checks.
- A new storage backend subclasses
StorageBackendand passestests/storage_contract.pythrough aStorageContractsubclass. Do not weaken a contract case to make a backend pass: fix the backend, or branch oncapabilitieswhen backends legitimately differ. - Keep the checks that live in the base class:
normalize_pathrefuses..,parse_storage_urirefuses credentials in the authority (and its error does not repeat them),deleterefuses the storage root, andLocalStoragedeletes a symbolic link without following it. Never log a storage URI's credentials or a backend's secrets. - A backend that can show one stored file through two instances (two roots, two prefixes, a link) overrides
_identity, so a copy or a move of a file onto itself is refused instead of deleting it. - When paths come from outside the process, use
LocalStorage(root)behind a scheme or authority of its own (Storage.mount("sandbox://jobs", LocalStorage(root))), not the rootlesslocal://backend. - At module level,
automation_file/storage/imports only the standard library,exceptions,logging_config,core.checksumandlocal.safe_paths;tests/test_storage_imports.pyfails on anything else. A backend SDK is imported lazily, inside the function that needs it.
SFTPClientusesparamiko.RejectPolicy()— unknown hosts are rejected, never auto-added. Callers passknown_hosts=explicitly or rely on~/.ssh/known_hosts. Do not swap inAutoAddPolicyfor convenience.
retry_on_transientonly retries the exception types passed viaretriable=(…). Never widen to bareException— masks logic bugs as transient failures. Always exhausts toRetryExhaustedExceptionchained withraise ... from err.Quota(max_bytes=…, max_seconds=…)— preferQuota.wraps(...)over inline checks when guarding a whole operation.0disables each cap.
- Credentials are stored at the caller-supplied
token_pathwithencoding="utf-8". Never log or print the token contents. GoogleDriveClient.require_service()raises rather than silently operating with aNoneservice — do not paper over it by catchingRuntimeErrorat the call site.
- Always use
pathlib.Pathfor path manipulation; never string-concatenate paths with user input. - Use
with open(...) as f:for every file operation; close via context manager. - Always pass
encoding="utf-8"when reading or writing text. - Never follow symlinks from untrusted sources — resolve and re-check the parent.
- JSON writes go through
automation_file.core.json_store.write_action_jsonwhich holds a module-level lock.
PackageLoader.add_package_to_executor(package)registers every function / class / builtin of a package under<package>_<member>. Treat it as eval-grade power: never expose it to arbitrary clients (e.g. via the TCP server). If you add a remote plugin-load command, gate it behind an explicit admin flag and authenticated transport.
- Google OAuth tokens live on disk at the user-supplied path; keep the path out of logs.
- API keys / credentials must come from env vars or caller-supplied paths; never hardcode.
- Pin dependencies in
requirements.txt/dev_requirements.txt. - Do not add new dependencies without reviewing their security posture.
- Avoid transitive bloat — prefer stdlib when the alternative is a single-function dependency.
All code must satisfy common static-analysis rules. Review every change against the checklist below.
- Cyclomatic complexity per function: ≤ 15 (hard cap 20). Break large branches into helpers.
- Cognitive complexity per function: ≤ 15. Flatten nested
if/for/trychains with early returns. - Function length: ≤ 75 lines of code (excluding docstring / blank lines). Extract helpers past that.
- Parameter count: ≤ 7 per function/method. Use a dataclass when more are needed.
- Nesting depth: ≤ 4 levels. Refactor with early returns instead of pyramids.
- File length: ≤ 1000 lines.
- Never use bare
except:— always specify exception types. - Avoid catching
Exception/BaseExceptionunless immediately logging and re-raising, or running at a top-level dispatcher boundary (theActionExecutor.execute_actionloop is one of these — it intentionally records per-action failures without aborting the batch). - Never
passsilently insideexcept— log viafile_automation_loggerat minimum. - Do not
return/break/continueinside afinallyblock — it swallows exceptions. - Custom exceptions must inherit from
FileAutomationException. - Use
raise ... from err(orraise ... from None) when re-raising to preserve / suppress the chain explicitly.
- Compare with
Noneusingis/is not, never==/!=. - Type checks use
isinstance(obj, T), nevertype(obj) == T. - Never use mutable default arguments — use
Noneand initialise inside. - Prefer f-strings over
%formatting orstr.format()(except inside lazy log calls:logger.info("x=%s", x)). - Use context managers for every file / socket / lock.
- Use
enumerate()instead ofrange(len(...))when the index is needed. - Use
dict.get(key, default)overkey in dict and dict[key].
snake_casefor functions, methods, variables, module names.PascalCasefor classes.UPPER_SNAKE_CASEfor module-level constants._leading_underscorefor protected / internal members.- Do not shadow built-ins (
id,type,list,dict,input,file,open, etc.).
- String literal used 3+ times in the same module → extract a module-level constant.
- Identical 6+ line blocks in 2+ places → extract a helper.
- Remove unused imports, unused parameters, unused local variables, unreachable code after
return/raise. - No commented-out code blocks — delete them.
- No
TODO/FIXME/XXXwithout an issue reference (# TODO(#123): …).
- Never use
print()for diagnostics in library code — usefile_automation_logger. - Use lazy logging (
logger.debug("x=%s", x)) to avoid eager f-string formatting on hot paths. - Never use
assertfor runtime validation;assertis for tests only.
- No hardcoded passwords, tokens, API keys, or secrets.
- No hardcoded IPs / hostnames outside of documented
localhost/ loopback defaults. - Magic numbers (except 0, 1, -1) should be named constants when repeated or non-obvious.
return bool(cond)orreturn cond, notif cond: return True else: return False.if x/if not x, notif x == True/if x == False.- A function should have a consistent return type.
- One import per line; grouped
from x import a, bis fine. - Order: stdlib → third-party → first-party (
automation_file.*) — separated by blank lines. - No wildcard imports outside
__init__.pyre-exports. - Max one level of relative import.
- Before committing any non-trivial change, run
ruff check automation_file/ tests/locally. - When adding a
# noqa: RULE, justify it in the comment — never blanket-disable.
- README parity. This repository ships
README.md(English) alongside the translatedREADME.zh-CN.mdandREADME.zh-TW.md. All three must stay current with the code. - When a change alters anything user-facing — features, commands, CLI flags, install/setup steps, configuration, or requirements — update
README.md, both translated READMEs (README.zh-CN.mdandREADME.zh-TW.md), and the affecteddocs/sources, all in the same commit, keeping their section structure and content aligned across languages. The translations must reflect the English content, not merely match its headings. - Never update one language, or
README.mdalone, and leave the other READMEs or the docs stale. There is no automated README-parity guard, so verify this by hand before committing.
Workspace rule shared by every repository under D:\Codes (full text: D:\Codes\CLAUDE.md).
- Commit at every stage. A stage is the smallest piece of work that leaves the repository consistent and passes this project's checks (definition of done, tests, lint): one finished
progress.mditem, or one self-contained step of a larger one. Commit it before starting the next stage, before switching to another repository, and before the session ends. Do not leave work uncommitted across sessions; if a stage cannot be finished, commit the consistent part and record the rest inprogress.md.- Stage only the files that stage touched (
git add <path>, nevergit add -A), follow this file's commit-message rules, and never add AI attribution. - Committing is not pushing: push or open a PR only as this project's branch flow says or when asked.
- Commit and push frequently. After each big feature — a self-contained stage that passes this project's checks — commit and push to the remote; do not pile up a large batch of work before committing or pushing. Smaller batches collide less with other sessions, let CI catch problems earlier, and are easier to revert. Follow this project's normal branch flow (usually
dev). - SonarCloud / Codacy findings. When a PR or commit fails a SonarCloud or Codacy check, look the findings up through their APIs instead of guessing. The keys are in environment variables:
SonarCloudToken(SonarCloud, e.g.curl -s -u "$SonarCloudToken:" "https://sonarcloud.io/api/issues/search?componentKeys=<key>&pullRequest=<n>&resolved=false") andCODACY_PROJECT_TOKEN(a Codacy project token, valid only for its own project: any other repository answers "Bad credentials", so for a public repository queryhttps://app.codacy.com/api/v3/analysis/organizations/gh/<org>/repositories/<repo>/pull-requests/<n>/issues?status=newwithout a key). Never reveal a key or any personal credential while doing so: refer to the variables by name only, never echo or print their values, and never put them in files, commit messages, PR or issue text, logs, or any output that leaves the machine.
- Stage only the files that stage touched (
progress.md(repository root, tracked) holds outstanding work only: no finished items, no history, no rules.docs/updates/records finished work: one batch file per month (YYYY-MM.md), one entry per piece of work headed## U-YYYYMMDD-NN · date · title · #tags, and an index with query commands indocs/updates/README.md. When aprogress.mditem is done, delete it and add a#doneentry plus its index row in the same commit.architecture.md(repository root) is the short architecture overview: layers, entry points, main flows, extension points, cross-project boundaries. Update it in the same commit whenever a change alters any of those.- Cross-project contracts are listed in
architecture.md§6: what other repositories rely on here (CLI flags, import paths, constructor arguments, file layouts) and what this repository relies on elsewhere. No test here protects them, so never rename or remove one without changing its consumers in the same round, and update §6 whenever a contract is added or changes.
- Commit messages: short imperative sentence (e.g., "Fix rename_file overwrite bug", "Update stable version").
- Do not mention any AI tools, assistants, or co-authors in commit messages or PR descriptions.
- Do not add
Co-Authored-Byheaders referencing any AI. - PR target:
devfor development work,mainfor stable releases.