120 Commits
Author SHA1 Message Date
poli0981 f59bc54e0d Merge pull request 'ci: move CommandForge to Gitea — workflows, R2 releases, links, docs; release 2.3.0' (#2) from chore/gitea-migration into main
Reusable / Qodana / Qodana (push) Successful in 4m47s
Qodana / qodana (push) Successful in 4m47s
Security / workflow-lint (push) Successful in 7s
Reusable / Security / Rust (cargo-deny) (push) Skipped
Reusable / Security / Secrets (gitleaks) (push) Successful in 9s
Reusable / Security / SAST (Opengrep) (push) Successful in 16s
Reusable / Security / Dependencies (osv-scanner) (push) Successful in 12s
Reusable / Security / .NET (NuGetAudit) (push) Successful in 41s
Security / scan (push) Successful in 1m19s
Build / build (push) Skipped
Build / package (push) Skipped
Release / Build, pack and upload to R2 (push) Successful in 2m2s
Reusable / Publish to R2 / publish (push) Successful in 11s
Release / SHA256SUMS and SBOM to R2 (push) Successful in 11s
Release / Gitea release (notes + links) (push) Successful in 6s
Reusable — Announce Release to Discord / announce (push) Successful in 7s
Release / announce (push) Successful in 7s
Reviewed-on: #2
2026-11-26 02:45:39 +00:00
poli0981andClaude Opus 5.5 7bad284c21 chore(release): 2.3.0
Build / build (pull_request) Successful in 1m40s
Build / package (pull_request) Successful in 7m16s
Reusable / Qodana / Qodana (pull_request) Successful in 6m36s
Qodana / qodana (pull_request) Successful in 6m36s
Security / workflow-lint (pull_request) Successful in 7s
Reusable / Security / Rust (cargo-deny) (pull_request) Skipped
Reusable / Security / Secrets (gitleaks) (pull_request) Successful in 9s
Reusable / Security / SAST (Opengrep) (pull_request) Successful in 18s
Reusable / Security / Dependencies (osv-scanner) (pull_request) Successful in 12s
Reusable / Security / .NET (NuGetAudit) (pull_request) Successful in 41s
Security / scan (pull_request) Successful in 1m22s
CommandForge moves off GitHub: updates from releases.poli0981.dev (Cloudflare
R2), the source on Gitea, issues on the GitLab mirror, CI on Gitea Actions,
Renovate for dependencies, SHA256SUMS and a CycloneDX SBOM with every
release. Installs of 2.2.0 and older can't update themselves (they ask
GitHub) and need this version once by hand; the notes say so.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-26 09:26:39 +07:00
poli0981andClaude Opus 5.5 e5593b1f74 deps: SonarAnalyzer.CSharp 10.37.0.15768
Released 2026-11-20. The solution builds with no new warning. Everything else
is current: .NET 10.0.15 with SDK 10.0.404 (the November 2026 security
update), Velopack 1.2.161, WPF-UI 4.3.0; no vulnerable or deprecated package,
direct or transitive. Microsoft.Extensions.* 11.0 belongs to .NET 11 and
stays out (the app is on the .NET 10 LTS line).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-26 09:25:32 +07:00
poli0981andClaude Opus 5.5 49301f266b docs: the project lives on Gitea, issues on GitLab, releases on R2
README (badges from Gitea Actions and shields' Gitea release badge,
"Where things live", downloads from releases.poli0981.dev, checksums and
the CycloneDX SBOM instead of `gh attestation verify`, a note that 2.2.0 and
older must update once by hand), USAGE, UPDATES (the HTTP feed, the file
layout on R2, the delta from `vpk download s3`), RELEASING (the new release
workflow, its dry run, user-level R2 secrets), BUILD (the CI table on Gitea
Actions, Renovate), PRIVACY (the update check goes to releases.poli0981.dev
through Cloudflare), SECURITY (e-mail only, never a public issue on the
mirror; Qodana, gitleaks, Opengrep, osv-scanner, NuGetAudit, Renovate instead
of CodeQL, Scorecard, SonarCloud, Snyk and Dependabot; no attestations),
CONTRIBUTING (Gitea read-only, issues and merge requests on GitLab, patches
by e-mail), CODE_OF_CONDUCT, EULA, DISCLAIMER and MAINTAINERS lose their
GitHub references, THIRD-PARTY-NOTICES swaps SonarScanner for CycloneDX,
Directory.Build.props points RepositoryUrl at Gitea, and CLAUDE.md gets the
new rules 6 and 7 and a "Forge & CI" section. CHANGELOG entries stay as they
were; only the compare links at the bottom point at Gitea.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-26 09:24:40 +07:00
poli0981andClaude Opus 5.5 de7f12c324 docs: issue and merge request templates for the GitLab mirror
Gitea's registration is closed, so issues and merge requests from everyone
go to gitlab.com/poli0981/CommandForge, and GitLab does not read GitHub's
issue forms. .gitlab/issue_templates gets Markdown versions of the five forms
(Bug, Feature request, Command, Translation, Accessibility) and
.gitlab/merge_request_templates/Default.md the pull request checklist, with
a note that CI runs on Gitea. ACCESSIBILITY.md sends a barrier to the GitLab
Accessibility template or accessibility@, and its test follows.

The .github forms stay for Gitea, which reads them: their links point at
Gitea's paths, private reports at security@ (GitHub's private vulnerability
reporting and Discussions are gone), and config.yml points at the mirror.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-26 09:20:50 +07:00
poli0981andClaude Opus 5.5 cad42ac9cf fix: updates from Cloudflare R2, links to Gitea and the GitLab mirror
The GitHub account is gone, and with it the update feed and every link the
app opened. Velopack now reads https://releases.poli0981.dev/commandforge
(an HTTP source, ProductLinks.UpdateFeed); 404 / 403 / 429 / 5xx / offline
are still told apart, and their messages name "the update server" instead of
GitHub (Cloudflare's edge answers 403 when it refuses and 429 when it
limits).

ProductLinks: the source, user guide, accessibility statement and the four
legal texts on Gitea (the Legal pages read them from ProductLinks instead of
four hard-coded GitHub URLs); issues on the GitLab mirror, since Gitea's
registration is closed. Report a bug opens a new GitLab issue with the title
and the answered Bug template (.gitlab/issue_templates/Bug.md) as its
description; a test keeps the app's sections and checklist equal to the
template's.

Strings in all five languages: "Source code" (was "GitHub"), "Read the full
text online", "Open issue on GitLab", and the privacy and auto-check texts
name releases.poli0981.dev. Keys Settings_GitHub and LegalGateReadOnGitHub
become Settings_SourceCode and LegalGateReadFullText. A new test fails if any
source file links to github.com/poli0981 again.

The terms version stays 1.1: the update check sends the same request, only
to another host.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-26 09:18:05 +07:00
poli0981andClaude Opus 5.5 2d09b0a7f4 build(deps): Renovate replaces Dependabot
Dependabot was GitHub's. The self-hosted Renovate on Gitea applies the shared
preset local>poli0981/renovate-config (pinned action digests, non-major
updates grouped, OSV security PRs, a 3-day release age for NuGet). On top of
it, as the Dependabot rules did: majors wait for approval on the Dependency
Dashboard (maintenance mode), Microsoft.Extensions.* and the SDK in
global.json never take a major (the .NET 10 LTS line), and Velopack moves
together with the vpk CLI. Validated with renovate-config-validator
44.260.3 --strict.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-26 09:13:18 +07:00
poli0981andClaude Opus 5.5 d39f188ea6 ci(release): Velopack to Cloudflare R2, CycloneDX SBOM, SHA256SUMS, Gitea release
GitHub Releases is gone. A v* tag now builds and packs on the Windows runner
as before (scripts/pack.ps1), then `vpk upload s3` puts the packages and the
feed on R2 (releases.poli0981.dev/commandforge, feed last), the ops
publish-r2.yml adds <version>/SHA256SUMS and the SBOM, a Gitea release gets
the notes and the links (no binaries), and the ops announcer posts to
Discord. R2 credentials stay in VPK_* environment variables of this
tag/dispatch-only workflow.

scripts/release-assets.ps1 (also runs locally) writes the CycloneDX SBOM
(CycloneDX tool 6.3.2, replacing GitHub's dependency-graph SBOM, decision
D7), SHA256SUMS of the files this version ships, and the notes from
CHANGELOG.md. The feed files are no longer hashed: vpk rewrites them on
upload, which is what made checksums.txt wrong for RELEASES and
releases.win.json in 2.1.0 and 2.2.0.

A manual run on a branch is a dry run: it builds, packs, reads the previous
release from R2 and keeps the files as an artifact, but uploads nothing.
Attestations go (no OIDC on Gitea). VirusTotal stays optional.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-26 09:13:13 +07:00
poli0981andClaude Opus 5.5 aae42f7e2f ci: Discord notifiers through the ops repo's Gitea workflows
announce-release and notify-ci-failure call the ops repo's .gitea reusables at
ops v2026.11.4 (c133a00), with ops_ref at the same commit so the notifier
script matches, and pass only the secrets each one declares instead of
inheriting all of them. notify-ci-failure watches Build, Qodana and Security
(SonarCloud is gone). New: notify-release-pipeline reports every Release run
to DISCORD_RELEASE_PIPELINE_WEBHOOK.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-26 09:07:59 +07:00
poli0981andClaude Opus 5.5 43606c5b9f ci(qodana): run the Qodana CLI through the ops reusable workflow
JetBrains/qodana-action needs GitHub's APIs (annotations, the PR comment, the
cache). The ops repo's reusable-qodana.yml runs the pinned, checksum-verified
Qodana CLI natively on the Windows runner instead, builds the solution first
and keeps the report as an artifact; the results still go to Qodana Cloud.
The token check job goes: Gitea has no fork pull requests, and runs started
by renovate-bot skip the scan in the reusable itself.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-26 09:07:39 +07:00
poli0981andClaude Opus 5.5 3776562fb6 ci: Security workflow — workflow lint and the ops security scan
actionlint and shellcheck (pinned, SHA-256 verified) lint .gitea/workflows,
and the ops repo's security.yml runs gitleaks over the full history, Opengrep,
osv-scanner and a NuGetAudit restore on the Windows runner. Push to main,
pull requests, and weekly on Friday 14:11 UTC (inside the runner's
13:00-16:00 UTC window, a free slot in the ops cron registry). This replaces
CodeQL for both the C# and the workflow analysis.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-26 09:07:09 +07:00
poli0981andClaude Opus 5.5 48efda1071 ci: drop CodeQL, dependency review, Scorecard and SonarCloud
None of them runs on Gitea: CodeQL and Scorecard upload to GitHub code
scanning (and Scorecard needs OIDC), dependency review reads GitHub's
dependency graph, and SonarQube Cloud is dropped in every repository
(ops migration decisions D1 and D7). The dotnet-sonarscanner tool goes with
it. Opengrep, gitleaks, osv-scanner and NuGetAudit (the Security workflow)
and Qodana take over.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-26 09:06:45 +07:00
poli0981andClaude Opus 5.5 83286ed1c3 ci: build and test on Gitea Actions
Move build.yml to .gitea/workflows. The Windows jobs run in host mode on the
maintainer's PC, so setup-dotnet installs into the runner tool cache, the
NuGet cache is the PC's own (no actions/cache), and artifacts go through the
Gitea fork of upload-artifact (upstream v4+ refuses non-GitHub servers).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-26 09:06:37 +07:00
poli0981 ea60d58ac7 Merge pull request #65: docs — maintenance mode from 2.2.0; Report a bug fills the bug form; release 2.2.0
docs: maintenance mode from 2.2.0; Report a bug fills the bug form; release 2.2.0
2026-11-16 11:22:25 +07:00
poli0981andClaude Opus 5.5 f9eb5e19eb test(report-bug): run the Report a bug command, not only its builders
SonarCloud's gate counted the command's body as new code without a test
(77.8% of new lines covered, 80% required). A test now runs
OpenIssueCommand with fakes and checks the address it opens: the Bug
report form, the crash title and code, this app's version and Windows.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-16 11:10:29 +07:00
poli0981andClaude Opus 5.5 e696b33196 chore(release): 2.2.0
CHANGELOG [2.2.0] — 2026-11-16 (an empty [Unreleased] stays above it) with
its compare link, and <Version>2.2.0</Version>.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-16 11:04:42 +07:00
poli0981andClaude Opus 5.5 de3a7a69ca docs: maintenance mode from 2.2.0 — policy, status, badges, issue forms
CommandForge is stable and in maintenance mode. CONTRIBUTING.md holds the
policy (Maintenance mode: what we accept): dependency and security updates
(High/Critical: an urgent patch; Moderate: the next routine update), major
platform updates, catalog commands added, fixed or removed, bug, UI/UX,
accessibility and translation fixes; a new feature only when genuinely
necessary. README gets a Project status section and a row of badges with
alt text; SECURITY.md supports 2.2.x; the PR template asks for the scope and
the accessibility checks.

Issue forms: Command — add, fix or remove and Translation fix are new
(labels catalog and translation); Feature request asks why it is necessary;
the bug form's version and log hints are current; config links Discussions
› Ideas and the accessibility statement. CLAUDE.md records the status, the
accessibility rules and accessibility@.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-16 11:04:42 +07:00
poli0981andClaude Opus 5.5 0e048d85ad fix(report-bug): open the Bug report form with its fields filled in
The app opened issues/new?title=&body=. In a repository with issue forms
GitHub ignores body, and anyone who isn't a collaborator sees the list of
forms first, so the description, the crash code and the versions were lost.
It now opens ?template=bug_report.yml and fills the form's fields by id
(what-happened, app-version, windows-version, logs); a test keeps those ids
in step with .github/ISSUE_TEMPLATE/bug_report.yml.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-16 11:04:42 +07:00
poli0981 9c1e619880 Merge pull request #64: fix(a11y) — screen readers, keyboard, names and larger text; ACCESSIBILITY.md
fix(a11y): screen readers, keyboard, names and larger text; ACCESSIBILITY.md
2026-11-16 10:58:35 +07:00
poli0981andClaude Opus 5.5 cb9d818fc5 test(a11y): a peer's name may be null in the runtime tests' text walk
Qodana: AutomationPeer.GetName() is annotated as possibly null, and the
helper yields it as a non-null string; an unnamed text now yields "".

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-16 10:48:49 +07:00
poli0981andClaude Opus 5.5 ded58c145f fix(a11y): settle Qodana's findings on the accessibility changes
- The four "Read the full text on GitHub" links get their names from one
  binding each, through RowActionNameConverter ("…: EULA"), and the
  "Did you mean" button's name moves into its style. Qodana's XAML engine
  reported a nameless field ("Field ' ' is assigned but its value is never
  used") for a MultiBinding written as a property element on an element
  without x:Name; what is read is unchanged.
- DangerBadge no longer declares the WPF-UI namespace its icon swap left
  unused.
- A redundant namespace qualifier in AccessibilityDocumentTests.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-16 10:39:10 +07:00
poli0981andClaude Opus 5.5 36bc62d7ba test(a11y): run the WPF fixes on real WPF-UI controls; Restore down
SonarCloud's gate asks for 80% coverage on new code, and the first push had
22.5%: most of the new code only runs inside WPF. New tests run it on an STA
thread against WPF-UI's own styles and templates, with no window shown: the
names given to template parts, the glyphs kept out of the automation tree,
the decorative peers, the Ctrl+Q scope, the screen-reader notification, and
the font and contrast resources. A WPF-UI update that renames one of those
parts now fails a test instead of silently undoing the fix.

The seams for that: WpfUiAccessibility.Apply (what the class handlers run),
ScreenReader.Raise and RaiseOnActiveWindow, FontScaleService taking its
text-size reader and the resources it writes, ThemeService.ApplyDimming
taking the resources.

The tests also showed that WPF-UI 4.3 has a single button for Maximize and
Restore down, drawn as Restore down while the window is maximized; its name
now follows.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-16 10:33:45 +07:00
poli0981andClaude Opus 5.5 79670fbe6f docs(a11y): accessibility statement, issue form and user guide
ACCESSIBILITY.md says what CommandForge aims for (WCAG 2.2 AA through
WCAG2ICT: a goal, not a claim), what works with the keyboard, screen
readers, contrast themes and larger text, how that is checked, the known
limitations with what to do instead, and how to report a barrier: the new
Accessibility problem issue form or accessibility@poli0981.dev. USAGE.md
gains an Accessibility section and the F6 shortcut, and the changelog lists
the fixes. A test keeps the statement free of conformance claims and its
links working.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-16 10:14:20 +07:00
poli0981andClaude Opus 5.5 4507faa6b3 fix(a11y): screen readers, keyboard, names and text size across the app
An accessibility review of every screen, with the keyboard alone, Narrator
and Axe.Windows:

- Screen readers hear what appears: a run starting, waiting for admin
  permission and finishing (result, exit code, time, restart needed), a
  search's result count, the Command Palette's highlighted result and its
  position, every notification and an update's progress. WPF ignores
  LiveSetting, so these go through AutomationPeer.RaiseNotificationEvent.
- The console and the Log viewer are read line by line; an error line says
  so and has a bar at its left, not only a colour; a blank line is read as
  one.
- Lists and buttons are read by their text instead of a type name; catalog
  rows carry their risk and badges as item status; a button repeated on
  every row names its row ("Undo: Flush DNS cache").
- WPF-UI template parts get names: the pane toggle and its two lists, the
  caption buttons, the clear button, the card expander headers. Icon glyphs
  (private-use characters) are kept out of the UI Automation tree
  (DecorativeIcon, GlyphHost), and an info bar's title and message, which
  the tree leaves out, are read through its severity icon.
- Keyboard: F6 moves between the pane, the page and the console; the focus
  moves into the page after navigation; Enter opens a command in the
  catalog and in History; Tab reaches a row's buttons; the splitters move
  with the arrow keys; every window and dialog starts with the keyboard
  inside it, a Caution confirmation on Cancel; Ctrl+Q does not quit while
  typing; page frames are no longer empty Tab stops.
- Seeing the screen: Windows' Text size multiplies the app's font size
  (the navigation pane widens at the largest sizes, badges and filters
  wrap); dimmed text is drawn at full strength under contrast themes;
  secondary text is darker; cut-off text has a tooltip; page transitions
  follow Windows' Animation effects setting.
- Tests: XAML rules (names, list items, headings, splitters, colours,
  icons) and the pure helpers behind the announcements and sizes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-16 10:14:20 +07:00
poli0981 24cf5f04f7 Merge pull request #63: ci — Qodana for .NET analysis; .NET 10.0.15 runtime and dependency updates
ci: Qodana for .NET analysis; .NET 10.0.15 runtime and dependency updates
2026-11-16 09:37:52 +07:00
poli0981andClaude Opus 5.5 d95db53a2e docs(changelog): Qodana's first fixes and the shell hardening
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-16 09:19:20 +07:00
poli0981andClaude Opus 5.5 7d9fe19023 ci(qodana): settle the first report - inspection choices, engine fault, read security sites
The first run (Ultimate licence, native on windows-latest) reported 380 problems. Every one was
read: real ones are fixed in the previous commits; the rest argue with choices this project
made, and are switched off where the engine that raised them reads it, each with its reason:

- .editorconfig (ReSharper's inspections, read by Rider too): XAML bindings and WPF UI resources
  the engine can't resolve, "unused"/"can be private" for members XAML and tests reach, style
  proposals the build's own analyzers don't take, guards on JSON read from disk, MVVM Toolkit
  hooks, translations equal to English in .resx, closures in tests.
- qodana.yaml: the files JetBrains' security rules were read in (with the tripwire test), and
  ProcessJob.cs, where the engine fails on CsWin32's null-to-PCWSTR conversion and reports the
  whole file as unused.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-16 09:19:19 +07:00
poli0981andClaude Opus 5.5 cb1386cc9a fix: findings from Qodana's first report
- SystemProcessRunner: build the ProcessStartInfo before the Process, so a program that can't
  be resolved leaves no undisposed Process behind (an object initializer runs outside `using`).
- JsonExecutionHistoryService: read the history under the lock it is replaced under.
- SingleInstanceGuard: a collection expression for the wait handles.
- AboutView: explicit Grid.Row/Grid.Column on every cell of the contact grid.
- Tests: no redundant casts, name qualifiers or unused lambda parameters.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-16 09:19:19 +07:00
poli0981andClaude Opus 5.5 2741691c81 fix(security): open only https/mailto addresses and existing folders through the shell
ShellService.TryOpen handed any string to ShellExecute, which runs whatever it is given: a file:
address or an unknown protocol handler is a program. Its twelve callers only ever pass the
project's links, mailto addresses and the app's own folders, so anything else is now refused
and logged (IsAllowedTarget, tested).

ProcessStartSitesTests lists every file that starts a process, with what it starts, and fails
on a new one until it has been read - the tripwire beside Qodana's security rule, which leaves
those read files out (qodana.yaml).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-16 09:19:19 +07:00
poli0981andClaude Opus 5.5 32f97fac69 docs(changelog): unreleased notes for Qodana and the November .NET update
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-16 08:45:45 +07:00
poli0981andClaude Opus 5.5 47dae756d9 ci: Qodana for .NET code analysis, native mode on Windows
qodana.yml runs JetBrains Qodana for .NET (qodana-dotnet, Rider's engine, Ultimate licence
through the QODANA_TOKEN secret) on pushes to main, pull requests and by hand:

- a `token` job skips fork and Dependabot runs without trusting actor names (as SonarCloud);
- the `qodana` job runs on windows-latest, because WPF (net10.0-windows) only loads there:
  restore, a Release build (a failing build is one red step), then the action pinned by SHA
  (v2026.2.2) with pr-mode off, so pull requests and main are judged by the same list;
- results go to Qodana Cloud, to annotations and a PR comment, and to the qodana-report
  artifact. It is advisory: not a required check.

qodana.yaml holds every setting: native mode, the qodana.recommended profile without the
Hints severity, app.manifest left out of XmlHighlighting, the solution and configuration,
output folders excluded, and a gate of zero problems.

Also: the CI-failure notifier watches Qodana; BUILD.md, RELEASING.md (QODANA_TOKEN),
SECURITY.md and CONTRIBUTING.md describe it, and BUILD.md the Dependabot major-version rule.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-16 08:45:45 +07:00
poli0981andClaude Opus 5.5 ee696465ad ci(dependabot): skip .NET and Microsoft.Extensions majors; use labels that exist
- ignore semver-major updates of Microsoft.Extensions.* and of the .NET SDK: the app stays on
  the .NET 10 LTS line, and moving to a new .NET major is a deliberate migration done by hand
  (Microsoft.Extensions 11.0.0 shipped with .NET 11).
- The configured labels `nuget`, `dotnet-sdk` and `github-actions` don't exist in the
  repository, so Dependabot dropped them; use the existing `.NET` and `github_actions`.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-16 08:45:45 +07:00
poli0981andClaude Opus 5.5 d054902117 build(deps): .NET 10.0.15 runtime (SDK 10.0.404), DI 10.0.15, SonarAnalyzer 10.36, test packages
- global.json: SDK 10.0.404, which carries the November 2026 .NET security update
  (runtime 10.0.15). CI already installs the newest 10.0 SDK (rollForward latestFeature),
  so this is the floor a local build needs.
- Microsoft.Extensions.DependencyInjection(.Abstractions) 10.0.15.
- SonarAnalyzer.CSharp 10.36.0.15337 (no new findings).
- Tests: xunit.v3.mtp-off 4.0.3, Microsoft.NET.Test.Sdk 18.12.0, coverlet.collector 10.1.1.
- THIRD-PARTY-NOTICES: versions brought up to date, including CsWin32 0.3.371 and the
  SonarScanner 12.1.0 from #62.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-16 08:45:34 +07:00
poli0981 df3b9e3753 Merge pull request #62: deps — bump the build-tooling group (SonarScanner for .NET 12.1.0, CsWin32 0.3.369)
deps: Bump the build-tooling group with 2 updates
2026-11-16 08:44:44 +07:00
dependabot[bot] 5724855f63 deps: Bump dotnet-sonarscanner and Microsoft.Windows.CsWin32
Bumps dotnet-sonarscanner from 12.0.0 to 12.1.0
Bumps Microsoft.Windows.CsWin32 from 0.3.367 to 0.3.371

---
updated-dependencies:
- dependency-name: dotnet-sonarscanner
  dependency-version: 12.1.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: build-tooling
- dependency-name: Microsoft.Windows.CsWin32
  dependency-version: 0.3.369
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: build-tooling
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-11-16 01:41:15 +00:00
poli0981 4de305d3ae Merge pull request #61: ci — bump the actions group (setup-dotnet 6.1.0, CodeQL action 4.39.3)
ci: Bump the actions group with 4 updates
2026-11-16 08:39:11 +07:00
dependabot[bot] 3ab59b443f ci: Bump the actions group with 4 updates
Bumps the actions group with 4 updates: [actions/setup-dotnet](https://github.com/actions/setup-dotnet), [github/codeql-action/init](https://github.com/github/codeql-action), [github/codeql-action/analyze](https://github.com/github/codeql-action) and [github/codeql-action/upload-sarif](https://github.com/github/codeql-action).


Updates `actions/setup-dotnet` from 6.0.0 to 6.1.0
- [Release notes](https://github.com/actions/setup-dotnet/releases)
- [Commits](https://github.com/actions/setup-dotnet/compare/a98b56852c35b8e3190ac28c8c2271da59106c68...0f4a354dd5547a28c70b7853dbd95d5b67886e73)

Updates `github/codeql-action/init` from 4.39.1 to 4.39.3
- [Release notes](https://github.com/github/codeql-action/releases)
- [Changelog](https://github.com/github/codeql-action/blob/main/CHANGELOG.md)
- [Commits](https://github.com/github/codeql-action/compare/9b3254085494b55a0f7c4c2b3d2d52cc712ce370...33d7b85da1a04171e211befe2c739303b9a4c066)

Updates `github/codeql-action/analyze` from 4.39.1 to 4.39.3
- [Release notes](https://github.com/github/codeql-action/releases)
- [Changelog](https://github.com/github/codeql-action/blob/main/CHANGELOG.md)
- [Commits](https://github.com/github/codeql-action/compare/9b3254085494b55a0f7c4c2b3d2d52cc712ce370...33d7b85da1a04171e211befe2c739303b9a4c066)

Updates `github/codeql-action/upload-sarif` from 4.39.1 to 4.39.3
- [Release notes](https://github.com/github/codeql-action/releases)
- [Changelog](https://github.com/github/codeql-action/blob/main/CHANGELOG.md)
- [Commits](https://github.com/github/codeql-action/compare/9b3254085494b55a0f7c4c2b3d2d52cc712ce370...33d7b85da1a04171e211befe2c739303b9a4c066)

---
updated-dependencies:
- dependency-name: actions/setup-dotnet
  dependency-version: 6.1.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: actions
- dependency-name: github/codeql-action/init
  dependency-version: 4.39.3
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: actions
- dependency-name: github/codeql-action/analyze
  dependency-version: 4.39.3
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: actions
- dependency-name: github/codeql-action/upload-sarif
  dependency-version: 4.39.3
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: actions
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-11-09 10:25:39 +00:00
poli0981 d769d58770 Merge pull request #60: feat(catalog) — Devices, Backup & Recovery, Accounts; 37 new commands; 2.1.0
feat(catalog): Devices, Backup & Recovery, Accounts — 37 new commands; release 2.1.0
2026-10-26 13:36:24 +07:00
poli0981andClaude Opus 5.5 e2bf8eb758 chore(release): 2.1.0
Moves the unreleased notes under 2.1.0 (with the new categories and
commands) and sets the dev-build version to 2.1.0.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-26 13:30:46 +07:00
poli0981andClaude Opus 5.5 225c6e632c docs: 298 commands in 15 categories
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-26 13:30:46 +07:00
poli0981andClaude Opus 5.5 a5f5e4b3c1 test(catalog): category list and order, per-build coverage, launcher arguments
- The 15 categories in order, with order values running from 1 without gaps
  (replaces the 12-category count and the Storage-only check).
- Every category has commands on Windows 10 22H2, 11 23H2 and 11 24H2,
  since the navigation pane hides commands for other builds.
- No two commands share a command line.
- explorer only opens settings URIs or shell folders, and control only
  Control Panel items.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-26 13:30:46 +07:00
poli0981andClaude Opus 5.5 a8ca7f4a79 feat(catalog): Devices, Backup & Recovery and Accounts categories, 37 commands
Three new categories and 37 commands (261 -> 298), with titles and
descriptions in all five languages and Fluent icons:

- Devices & Peripherals (11): Bluetooth, printer and display settings,
  the Sound panel; USB devices, cameras, audio devices, paired Bluetooth
  devices, printers and remembered-but-disconnected devices; Scan for
  hardware changes (pnputil, admin).
- Backup & Recovery (9): Recovery settings, WinRE status and Enable WinRE
  (reagentc, admin; enabling is Caution), System Protection, restore
  point disk usage (vssadmin behind a Win32_ShadowStorage check, since it
  exits 2 for both "no items" and access denied), File History, Backup
  settings, Backup and Restore (Windows 7), Recovery Drive.
- Accounts & Sign-in (8): Sign-in options, Your info, Other users,
  netplwiz, Credential Manager, cmdkey /list (never elevated, so it reads
  the user's own vault), net accounts, local groups.
- Existing categories (9): sleep states, last wake source, wake-armed
  devices, motherboard, language & region, disabled services, PATH
  entries with missing folders flagged, proxy and VPN settings.

Scripts start with $ErrorActionPreference='Stop' and filter PnP devices
client-side (Get-PnpDevice -Class throws when nothing matches). No command
needs an OS-build limit; all exist on Home editions.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-26 13:30:46 +07:00
poli0981 ab082676d6 Merge pull request #59: ci — SonarCloud CI analysis with coverage, .NET 10.0.14 and dependency updates
ci: SonarCloud CI analysis with coverage; .NET 10.0.14 and dependency updates
2026-10-26 13:27:52 +07:00
poli0981andClaude Opus 5.5 24fbf9ca23 docs(changelog): SonarCloud CI analysis, dependency and runtime updates
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-26 13:17:45 +07:00
poli0981andClaude Opus 5.5 c61d397199 build(deps): .NET SDK 10.0.403, DI 10.0.14, CsWin32 0.3.367, CodeQL 4.39.1
- global.json: SDK 10.0.403, so self-contained releases ship the
  .NET 10.0.14 runtime (October 2026 security update).
- Microsoft.Extensions.DependencyInjection(.Abstractions) 10.0.13 -> 10.0.14.
- Microsoft.Windows.CsWin32 0.3.366 -> 0.3.367.
- github/codeql-action v4.39.0 -> v4.39.1 (CodeQL and Scorecard uploads),
  pinned to the release commit.
- THIRD-PARTY-NOTICES: the new versions and the SonarScanner for .NET.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-26 13:17:45 +07:00
poli0981andClaude Opus 5.5 3fadfa0090 ci: analyze with SonarCloud from CI, with test coverage
Automatic Analysis can't import coverage, so SonarCloud now runs from
sonarcloud.yml: the SonarScanner for .NET 12.0.0 (pinned as a local tool
next to vpk, updated by Dependabot's build-tooling group) wraps a Release
build and an OpenCover test run.

- A token job checks for SONAR_TOKEN, so fork and Dependabot pull
  requests are skipped without trusting actor or repository names.
- The project version is passed to the scanner, so the "previous version"
  new-code period resets at each release (and now, instead of judging the
  whole 2.0.0 rewrite as new code).
- Roslyn rules stay enforced by the warnings-as-errors build and aren't
  imported as external issues; XAML code-behind and the two Program.cs
  entry points are left out of coverage.
- .sonarcloud.properties (read only by Automatic Analysis) is removed;
  its exclusions move to the scanner arguments.
- CI failure alerts also cover the SonarCloud workflow.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-26 13:17:37 +07:00
poli0981 acb7ca4dd5 Merge pull request #58: ci, docs — release-workflow fixes, pinned shared workflows, stale comments
ci, docs: release-workflow fixes, pinned shared workflows, stale comments
2026-10-21 23:19:31 +07:00
poli0981andClaude Opus 5.5 c729a53228 docs(changelog): unreleased run-mode label and release-asset changes
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-21 23:14:17 +07:00
poli0981andClaude Opus 5.5 cae3679ffa fix(ui): say whether this copy updates itself, not "Portable / dev"
Settings > Advanced and Portable info showed "Installed" or
"Portable / dev". The official portable zip counts as installed
(it carries Velopack's updater), so "Portable / dev" only ever meant
a build run from source. The labels now read "Installed or portable
(updates itself)" and "Development build (doesn't update)", in all
five languages; the key is renamed to Settings_RunModeDev.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-21 23:13:53 +07:00
poli0981andClaude Opus 5.5 cad4708852 docs: the portable zip updates itself
The Velopack portable zip ships Update.exe and a .portable marker, so
it updates in place like the installed app; only a build run from
source can't update.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-21 23:12:11 +07:00
poli0981andClaude Opus 5.5 06731cdd0b chore: fix stale comments and the NuGet cache key
- ISettingsService: window size and maximized state are restored again
  since the window became resizable; WarnOnCancel only asks on close.
- IDialogService, CrashHandlingService, NaturalLanguageSearch (golden
  rule #7, not #5), the test project and pack.ps1 described the
  pre-2.0 setup (message boxes, the Generic Host, EN+VI only,
  Directory.Packages.props).
- build.yml hashed the removed Directory.Packages.props for its NuGet
  cache keys; it now hashes Directory.Build.props, where the
  SonarAnalyzer version lives.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-21 23:12:10 +07:00
poli0981andClaude Opus 5.5 d71da598da ci(release): drop a stale comment about draft lookups
The VirusTotal action no longer looks up the release; the links step
uses gh, which finds drafts too.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-21 23:08:18 +07:00
poli0981andClaude Opus 5.5 4daf4bbf39 ci(release): take the release notes from CHANGELOG.md
vpk creates the release without notes, so v2.0.0 was published, and
announced on Discord, with an empty body. Before publishing, the
workflow now sets the notes to the version's CHANGELOG section (the
text between its heading and the next one); it warns and leaves them
empty if there is no section. The VirusTotal links are appended after
it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-21 23:07:47 +07:00
poli0981andClaude Opus 5.5 ce0f905825 ci(release): add the VirusTotal links to the release notes
The action's update_release_body only works on `release` events, and
this workflow runs on tag pushes, so the scan links never reached the
notes: the v2.0.0 release body was empty. A step now appends a
"VirusTotal" section linking each scanned file's permanent report (by
SHA-256). The scan also no longer matches the previous version's full
package, which is only downloaded to compute the delta.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-21 23:05:21 +07:00
poli0981andClaude Opus 5.5 27816e92c6 ci(release): attest and hash only what the release publishes
The 2.0.0 release showed two gaps:

- Its provenance attestation also covered the 1.5.1 full package that
  `vpk download github` fetches only to compute the delta, which this
  run didn't build.
- checksums.txt listed that package and the local assets.win.json,
  neither of which is a release asset.

The portable zip that vpk also publishes had no attestation.

Now the attestation covers Setup.exe, the portable zip and this
version's packages only. checksums.txt hashes exactly the release's
assets plus the SBOM. UPDATES and RELEASING list the portable zip.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-21 23:03:48 +07:00
poli0981andClaude Opus 5.5 af8948378a ci: pin the shared workflows in poli0981/.github to a commit
The release announcer and the CI-failure notifier were called at
@main, so any later change to the shared repository would run inside
this repository's workflows (the announcer inherits its secrets)
without a change here (CodeQL actions/unpinned-tag, Scorecard
Pinned-Dependencies). They now point at the current main commit; bump
the SHA when the shared workflows change.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-21 22:58:57 +07:00
poli0981 05abfdfc4e Merge pull request #57: docs — 2.0.0 release notes, user guide, contact addresses
docs: 2.0.0 release notes, user guide, contact addresses
2026-10-21 22:56:55 +07:00
poli0981 a5860a70f0 Merge pull request #56: v2 UI — Fluent redesign with WPF-UI 4.3
v2 UI: Fluent redesign with WPF-UI 4.3
2026-10-21 22:53:06 +07:00
poli0981andClaude Opus 5.5 d82f2d45e5 docs: 2.0.0 release notes, user guide, contact addresses
- CHANGELOG: the 2.0.0 entry, plus the missing 1.5.1 compare link and
  a corrected [Unreleased] link.
- USAGE.md: a user guide for the new UI (the app's "User guide" link
  already points here).
- README: features as of 2.0 (261 commands, 12 categories, five
  languages, Fluent UI), download verification with
  `gh attestation verify`, and a contact table.
- Contact addresses on poli0981.dev: security@ (SECURITY.md, next to
  private vulnerability reporting), privacy@ (PRIVACY.md), legal@ (EULA,
  DISCLAIMER), copyright@/dmca@/takedown@ (a new takedown section in
  DISCLAIMER), code@ (CONTRIBUTING, CODE_OF_CONDUCT, MAINTAINERS).
- SECURITY: the current threat model and its known limits (per-user
  install, the winget alias), release attestations, SBOM and scanners.
- PRIVACY: every local file the app keeps, what the logs contain, and
  how the update check and bug reports work.
- BUILD, RELEASING, UPDATES: versions in each .csproj, the pinned vpk
  tool, pack.ps1 options, the CI workflows and rulesets, signed tags,
  the draft-then-publish release flow, and the new update behavior.
- THIRD-PARTY-NOTICES: WPF-UI and Fluent System Icons in, Material
  Design and Hosting out, current versions and build-time tools.
- CONTRIBUTING and the PR template: signed commits, required checks,
  five .resx files, catalog rules. The bug template points at
  More > About.
- CLAUDE.md: rule 6 allows provenance attestations; stack, namespace
  and conventions for v2.

The EULA's terms are unchanged (still version 1.1), so nobody is asked
to accept them again.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-21 22:49:29 +07:00
poli0981andClaude Opus 5.5 64ddbebde3 feat(ui): contact addresses in About
About lists security@poli0981.dev for vulnerability reports and
code@poli0981.dev for code questions; both open the mail app. The
addresses live in ProductLinks next to the other public links. New
strings in all five languages.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-21 22:48:25 +07:00
poli0981andClaude Opus 5.5 f7bbe53f96 feat(ui)!: Fluent redesign with WPF-UI 4.3
The app now follows Windows 11: Mica window with its own title bar, a
navigation pane, in-window dialogs, snackbars and the system accent color.
MaterialDesignThemes is gone.

- Shell: resizable FluentWindow (min 960x600) that remembers its size,
  position and maximized state. The title bar has a command search box
  (Ctrl+K), an admin-session indicator with "End admin session", and a More
  menu. The pane has Home, Favorites, History, Recipes, My commands and the
  catalog with its twelve categories and counts; the selection stays in sync
  with the view-model through NavigationKey.
- MainViewModel keeps the shell only; the catalog's browsing, filters,
  detail and run logic moved to CatalogViewModel. The catalog gets risk and
  admin-only filter chips, the estimated duration and an expanded command
  line in the detail panel, and a splitter between detail and console.
- One shared console for catalog, recipes and user commands: virtualized,
  batched, capped at 10,000 lines with a "N earlier lines" note, Copy all,
  Save to file, "Waiting for administrator permission…" status and Restart
  now (asks first, never while a command runs).
- Confirmation, update and bug-report dialogs are Fluent content dialogs;
  Cancel stays the default and Run appears for a Dangerous command only
  once its name or id is typed. The Legal Gate, terms viewer, crash dialog
  and command palette are Fluent windows; the Legal Gate lets you pick the
  language first.
- Theme: light, dark or system through ApplicationThemeManager, accent from
  Windows, High Contrast always wins. Font size scales every text and
  control live. Pages set the theme text color themselves (the navigation
  frame doesn't pass it down), and list text dims instead of recoloring so
  it stays readable on a selected row; search matches are bold and
  underlined.
- A finished run notifies with a snackbar (and flashes the taskbar button)
  when the console isn't visible; the taskbar shows progress while running.
- Catalog icons map to Fluent System Icons (IconMap), checked by a test.
- The presentation namespace is now CommandForge.Desktop: a namespace named
  CommandForge.Wpf hid WPF-UI's root namespace in XAML-generated code. The
  project, assembly and exe keep the name CommandForge.Wpf.
- IElevationService raises SessionChanged when the elevated helper starts or
  stops.
- Strings: about 45 new keys in all five languages; twelve unused keys
  removed. A test now scans the UI sources so every key the XAML or code
  uses must exist in every language.

BREAKING CHANGE: new look and layout; settings, history, recipes and user
commands carry over unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-21 22:26:42 +07:00
poli0981 0f2f2be5d4 Merge pull request #55: v2 core — hardened elevation, reliable execution and storage, catalog fixes + 20 commands
v2 core: hardened elevation, reliable execution and storage, catalog fixes + 20 commands
2026-10-21 22:04:57 +07:00
poli0981andClaude Opus 5.5 f781690b5f test: cover decoding, path resolution, elevation environment, storage
New tests for the output decoder (UTF-8, UTF-16LE with and without BOM,
OEM fallback, chunk boundaries), executable resolution, argument tokens,
the elevated child environment (including a real PowerShell run showing
it loads modules only from admin-only folders), crash-safe JSON files and
v1.5.1 settings, accent-insensitive search, recipe confirmations, the
update dialog, the console buffer and crash codes.

Run faults and cancellation must complete the output channel; elevation
tests have time limits; the DI test uses a scratch folder instead of the
real %AppData%; culture-switching tests run on their own; Domain and
Application may reference only the runtime (and Domain).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-21 21:21:25 +07:00
poli0981andClaude Opus 5.5 ee557ab532 perf(logging): refresh the Log Viewer once per burst, not per event
Every log event made the Log Viewer and Debug panel rebuild up to 1000
rows on the UI thread. The in-memory store now raises EntriesChanged once,
150 ms after the first event of a burst; Clear still notifies at once.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-21 21:21:25 +07:00
poli0981andClaude Opus 5.5 6d4843465a fix(catalog): reject contradictory or unsafe catalog records
A command is registered only after it passes validation, so a rejected
command can no longer be a revert target or shadow a valid duplicate, and
a revert that points at one is cleared. New checks: unknown argument
tokens, an executable that is not a plain program name, Caution or
Dangerous without confirmBeforeRun, Launch mode with an exit-code or
output restart policy, and a restartRegex under another policy. Invalid
embedded JSON yields an empty catalog plus an error instead of a crash.

The catalog tests also enforce -NoProfile -NonInteractive for PowerShell,
no wmic, no hard-coded C:, no %VAR% outside scripts, and that elevated
scripts read only the environment variables the Elevator sets from
trusted sources. DangerLevel documents what Safe, Caution and Dangerous
mean.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-21 21:21:24 +07:00
poli0981andClaude Opus 5.5 23adc8ef6d feat(catalog): safer cleanup and repair commands, 20 new commands
Automatic Disk Cleanup now enables an allow-list of safe handlers in its
own StateFlags slot (/sagerun:42), so Downloads, the Recycle Bin and
Windows.old are never touched and the user's own /sageset:1 choice is
kept. Removing Windows.old uses the "Previous Installations" handler and
is now Dangerous, as is clearing the event logs.

- Every PowerShell command runs with -NoProfile -NonInteractive. Scripts
  that printed success no matter what now stop on the first error, and
  cleanups report what they removed and what was in use.
- chkdsk.fix uses Repair-Volume -OfflineScanAndFix instead of piping a
  "Y" that is localized; drive letters come from {SystemDrive} and the
  battery report path from {UserProfile}.
- Windows Update reset keeps the old folders as .bak copies and always
  restarts the services; the Delivery Optimization cache uses its cmdlet;
  lid-close settings apply to the active power scheme; winget never
  prompts; activation status no longer needs VBScript; the Win11 Widgets
  button opens Settings, since Windows now blocks that change from scripts.
- New: restore point list, System Restore, Automatic Maintenance, clock
  resync, DNS cache, listening ports, Wi-Fi details, third-party scheduled
  tasks, Run keys, stopped automatic services, Windows Search restart,
  Store and optional updates, UAC settings, Core isolation, environment
  variables, WSL status, TRIM status, crash dumps and battery charge, with
  strings in all five languages.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-21 21:21:24 +07:00
poli0981andClaude Opus 5.5 c205dd0589 fix(wpf): AltGr-safe shortcuts, UI-language-only switching, user-command fixes, dead code
- Keyboard shortcuts require exactly Ctrl: AltGr arrives as Ctrl+Alt, so typing "@" on a German
  keyboard (AltGr+Q) closed the app and a Polish "ł" opened the Log Viewer. Ctrl+B (advertised in
  the menu and the shortcuts list) now toggles the sidebar.
- Switching language changes only the UI culture: number/date formats keep following the user's
  regional settings. Every window is tagged with the UI language (xml:lang) so Japanese text is not
  drawn with Chinese glyph shapes.
- User commands: a quoted "cmd" executable is recognised, "/q /c dir" no longer gains a second /c,
  and a command named like a resource key ("AppTitle") is no longer translated into that resource.
  Confirmations go through the dialog service.
- Remove the unused ExecutableKind enum and IRestorePointService port.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-21 20:44:50 +07:00
poli0981andClaude Opus 5.5 4349dddd43 fix(wpf): file/shell failures are reported, not crashes; imports are validated
- Settings, Log Viewer and Report Bug use the dialog/file/shell services: exporting logs or
  settings to a locked or read-only path, or opening a link with no browser configured, now shows
  a message instead of the generic crash dialog; file-dialog filters are localized.
- Imported settings files and profiles are normalized (null lists, unknown enum values, blank or
  duplicate favorites) before they are applied. PortableSettings properties are settable so keys
  missing from a file keep their defaults — the source-generated serializer reset init-only ones
  to false/0, which could silently turn off Caution confirmations.
- The prefilled "Report a bug" URL is capped (a full stack trace could exceed URL limits).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-21 20:41:45 +07:00
poli0981andClaude Opus 5.5 b204f48a0e fix(search): relevant matches, correct highlighting, accent-insensitive
- Descriptions and tags must contain the query words as real substrings (tags by word prefix);
  matching them as loose subsequences made "dns" hit ~140 of 241 commands.
- Titles rank exact > substring (word starts first) > all words present > fuzzy abbreviation, and
  the fuzzy matcher tries every starting point, so "flush" highlights the word "flush" instead of
  the first "f"/"l" it meets; weak scattered fuzzy matches are dropped.
- Accent- and case-insensitive throughout (TextFolding keeps indices 1:1 for highlighting): typing
  "don dep" finds "Dọn dẹp". Folded text is computed once per command, not per keystroke.
- Ties keep catalog order (stable sort); the "requires restart" filter means restart-always.
- Natural-language suggestions match whole words, so "ping" or "typing" no longer suggest battery.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-21 20:39:07 +07:00
poli0981andClaude Opus 5.5 62d7178eab fix(updates): end the elevated session before applying; robust errors; X cancels the download
- Download and apply are separate steps: applying first ends the elevated session and waits for the
  Elevator to exit (it runs from the folder Velopack replaces, and the non-elevated updater can't
  kill it or overwrite its locked files), and a command started during the download postpones the
  restart instead of being killed halfway.
- UpdateErrorMapper.Map(Exception) looks through wrapper/aggregate exceptions for the HTTP status;
  HttpClient timeouts now map to Offline instead of being rethrown as cancellations (which left the
  dialog stuck on "Checking"). User cancellation is still distinguished.
- Closing the update dialog with its title-bar X cancels the download; otherwise it finished in the
  background and restarted the app, possibly mid-command.
- The startup prompt never opens over another dialog; the "command running" guard reads the shared
  ExecutionViewModel (now a singleton) instead of MainWindow.DataContext.
- Settings' "Last checked" only updates when a check actually succeeded.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-21 20:36:20 +07:00
poli0981andClaude Opus 5.5 48fd03983f fix(safety): one set of confirmation/restore-point rules; recipes confirm every risky step
- RunSafety (Application) holds the rules for single runs, History re-runs, reverts and recipes:
  Dangerous always asks with typing; Caution asks unless turned off; a restore point is offered
  only for risky admin commands or catalog-flagged ones — never for per-user tweaks, where it
  only added a UAC prompt.
- Type-to-confirm accepts the title Unicode-normalized and case-insensitively, or the command id:
  Vietnamese input methods that type decomposed accents (and long CJK titles typed through an
  IME) could not confirm before. Run is a CanExecute gate in the view-model, Cancel is the
  default/Esc button, and the typing box gets focus.
- Recipes no longer run Dangerous steps after a single Yes/No: an overview prompt (No by default)
  is followed by the same confirmation each risky step gets on its own, and one restore point
  before the chain. Steps unavailable on this PC are kept when the recipe is saved again.
- Restore points: "Windows already made one in the last 24 hours" is reported as skipped (exit 2)
  instead of as created; any other failure asks before running the command anyway (No default).
- A run that does not start (already running, stopped at the restore point) is never recorded in
  Recent/History; History's Run again/Undo are disabled while a command runs; Clear asks first.
- Console output goes into an OutputBuffer: one notification per batch instead of per line,
  capped at 10,000 lines; an unexpected failure is reported in the console instead of crashing.
- Every run is logged as a one-line summary (id, exit code, duration — never its output).
- New IDialogService/IClipboardService/IShellService/IFileDialogService keep view-models free of
  MessageBox/Clipboard/Process calls (and testable); new strings in all five languages.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-21 20:32:38 +07:00
poli0981andClaude Opus 5.5 4a4e887134 fix(storage): atomic, corruption-tolerant, thread-safe local stores
All six JSON stores (config, history, recipes, profiles, user commands, settings import/export)
go through a shared JsonFile helper:
- Writes land in a temporary file that atomically replaces the original, so a crash or power loss
  mid-save can no longer truncate config.json (which silently reset every setting, including the
  accepted terms) or wipe history/recipes/profiles.
- A corrupt file is kept as name.corrupt-<timestamp>.json before defaults are used, instead of
  being overwritten on the next save; locked or unreadable files no longer crash startup.
- Background save failures are logged rather than thrown; a user-chosen export path still
  reports its error, and import files are never renamed.
- Every store serializes access with a lock and hands out copies, not its live list.
- config.json uses a source-generated serializer with the same PascalCase/enum-name format; loads
  repair null lists, unknown enum values and blank ids.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-21 20:23:01 +07:00
poli0981andClaude Opus 5.5 694d98388e fix(startup): custom entry point, no Generic Host, visible startup failures
- Program.Main runs VelopackApp.Build().Run() before WPF loads App.xaml (Velopack's own
  recommendation; vpk warned about OnStartup), then the single-instance check.
- The unused Generic Host (no hosted services, configuration or Microsoft.Extensions.Logging
  consumers) is replaced by a validated ServiceCollection; Microsoft.Extensions.Hosting and
  Serilog.Extensions.Hosting are dropped (~20 transitive packages).
- A startup failure now shows an error and exits instead of leaving an invisible process that held
  the single-instance mutex and silently swallowed every later launch; a malformed language code in
  config.json falls back to the system language.
- Serilog: 14 daily files of at most 10 MB (logs grew without bound before); flushed after the
  container is disposed so shutdown logging is kept.
- Second launches pass foreground rights to the running instance (AllowSetForegroundWindow) so it
  actually comes to the front instead of flashing in the taskbar.
- Crash handler: stable support codes (FNV-1a instead of the per-process randomized
  string.GetHashCode), a nested failure no longer closes the logger for the rest of the session,
  and the error dialog only takes an owner window that is visible.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-21 20:19:04 +07:00
poli0981andClaude Opus 5.5 81657aa058 fix(elevation): harden the broker and the Elevator
- Elevated children get an allow-listed environment rebuilt from trusted sources: per-user
  variables (COR_PROFILER/CORECLR_* DLL injection, PSModulePath module hijacking, windir/
  SystemRoot retargeting of recursive deletes) no longer reach commands run as administrator.
  PSModulePath is $PSHOME\Modules only, the one value Windows PowerShell 5.1 keeps as-is.
- Both ends verify the peer: the UI accepts only the Elevator process it launched
  (GetNamedPipeClientProcessId); the Elevator serves only CommandForge.Wpf.exe from its own folder
  (GetNamedPipeServerProcessId) and connects with Identification impersonation.
- The Elevator writes no files any more (an elevated append to the user-writable profile could be
  redirected with a junction); diagnostics go back to the UI's log as pipe Log messages.
- StartupHookSupport=false on the Elevator: DOTNET_STARTUP_HOOKS is ignored.
- Broker: cancelling while UAC/connecting returns Cancelled instead of throwing; a command that
  ignores a cancel for 10 s ends the session; pipe/JSON errors fail the run cleanly; the output
  channel is always completed.
- IElevationService: IsSessionActive and EndSessionAsync (needed before an update replaces the
  files the elevated process runs from) replace the unused IsElevationAvailable.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-21 20:19:03 +07:00
poli0981andClaude Opus 5.5 37950a05ff feat(execution): trusted executable paths, encoding-aware output, kill-on-close job
- ExecutableResolver: catalog executables resolve to absolute paths in System32/Windows (and
  the winget alias), so CreateProcess never searches the per-user, user-writable app folder —
  a planted reg.exe/powershell.exe there would otherwise run elevated. Launch-mode commands now
  pin their working directory too.
- OutputDecoder: stdout/stderr are read as raw bytes and decoded per line (UTF-16LE when the
  stream is UTF-16, else strict UTF-8 with an OEM-code-page fallback). sfc/wsl output and every
  native tool on Vietnamese/Japanese/Chinese Windows used to show as mojibake. Lone \r (progress
  updates) still breaks lines.
- ProcessJob: captured commands join a kill-on-close job object, so closing or crashing the app
  can no longer leave a half-finished command running.
- ArgumentTokens ({SystemDrive}, {SystemRoot}, {UserProfile}) filled from SystemPaths, which reads
  the kernel-reported system directory, known folders and HKLM — never %SystemRoot%-style
  variables a standard user can redefine. The command preview shows the expanded values.
- Exit code 3010 always flags a restart; Launch commands honour RestartPolicy.Always; output is
  only captured (bounded) when a restart regex needs it. ExecutionResult.OutputLines is gone
  (nothing read it, and it held the entire output in memory).
- RunCommandUseCase always completes the output channel and maps cancellation, so a failing run
  can no longer leave the console waiting forever.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-21 20:19:03 +07:00
poli0981 d7f816c7c8 Merge pull request #54 from poli0981/claude/v2-foundation
build/ci: v2 foundation — dependency refresh, xUnit v3, NuGet audit, hardened CI, Sonar fixes
2026-10-21 20:16:39 +07:00
poli0981andClaude Opus 5.5 d2dcebc6dd ci: address review and SonarCloud findings in workflows
- release.yml: upload the Velopack release as a draft, attach SBOM + checksums, then publish
  (publishing is what makes installed copies auto-update); VirusTotal runs after publishing
  because the release-by-tag API cannot see drafts.
- notify-ci-failure.yml: filter on the triggering event (`push`) instead of the forgeable actor
  login (SonarCloud githubactions:S8232).
- scorecard.yml: top-level `contents: read` instead of `read-all` (githubactions:S8234).
- codeql.yml: build with -p:RunAnalyzers=false; Roslyn analyzers add nothing to the extraction.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-21 20:02:41 +07:00
poli0981andClaude Opus 5.5 304693cfa0 build: keep package versions in each .csproj
GitHub's dependency graph reads NuGet versions from .csproj files but not from
Directory.Packages.props, so Central Package Management would have blinded Dependabot alerts,
dependency review and the release SBOM. Versions move back into the projects (same versions),
SonarAnalyzer.CSharp is now referenced from Directory.Build.props, and the xUnit v3 test
project declares OutputType Exe explicitly.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-21 20:02:41 +07:00
poli0981andClaude Opus 5.5 db35bd70af chore: remove the Vietnamese draft legal/ folder
legal/ held early drafts ("BẢN NHÁP", unfilled "[ĐIỀN NGÀY]" placeholders) that were superseded
by the English EULA.md, PRIVACY.md, DISCLAIMER.md and LICENSE at the repository root — the only
documents the in-app Legal Gate links to.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-21 19:56:43 +07:00
poli0981andClaude Opus 5.5 66415bbd61 build(release): pin vpk as a local tool, ReadyToRun publish, native x64 Velopack helpers
- .config/dotnet-tools.json pins vpk 1.2.161 to match the Velopack library (CI previously installed
  whatever vpk was latest).
- pack.ps1: ReadyToRun publish for faster startup, fail fast on any non-zero exit code, verify
  the Elevator is in the publish folder, `-SkipPack` for publish-only runs, and `--runtime` so vpk
  bundles x64 Update/Setup helpers instead of defaulting to x86 (the update channel stays "win").

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-21 19:56:43 +07:00
poli0981andClaude Opus 5.5 6157c53d55 ci: harden workflows; add packaging smoke test, CodeQL for Actions, dependency review, Scorecard
- Every action pinned to a full commit SHA; least-privilege permissions per job; concurrency
  groups and timeouts; secrets passed through env instead of being expanded inside run blocks.
- build.yml: NuGet cache, test results + coverage artifact, and a `package` job that publishes
  and packs with Velopack exactly like a release (catches a missing Elevator before tagging).
- codeql.yml: matrix over csharp (Windows, manual build) and actions.
- New dependency-review.yml (moderate+ vulnerabilities, GPLv3-compatible license allow-list) and
  scorecard.yml (OpenSSF Scorecard SARIF in code scanning).
- release.yml: pinned vpk via the tool manifest, build-provenance attestations, SPDX SBOM and
  checksums as release assets, and a direct call to the shared announcer (tag releases published
  with GITHUB_TOKEN never fired the `release` event, so Discord was never notified).
- notify-ci-failure.yml: grant actions: read (every run was a startup_failure) and skip
  Dependabot-triggered runs, which have no access to the webhook secret.
- dependabot.yml: grouped updates (Velopack + vpk move together), cooldown, labels, and .NET SDK
  (global.json) updates.
- .sonarcloud.properties for SonarCloud Automatic Analysis scope.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-21 19:56:42 +07:00
poli0981andClaude Opus 5.5 b4cbf68cce test: migrate the suite to xUnit v3
Pass TestContext.Current.CancellationToken to cancellable calls (xUnit1051), dispose pipes
asynchronously, drop null-forgiving operators that xUnit v3's nullability annotations make
redundant, and rename the ExecutionTests helper that shadowed the fake runner's RunAsync.
All 204 test cases pass under VSTest.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-21 19:56:42 +07:00
poli0981andClaude Opus 5.5 3fc7f0edf2 fix: resolve SonarCloud and SonarAnalyzer findings
- UpdateViewModel: every check/download owns a disposed CancellationTokenSource that Close
  cancels; an unexpected exception now shows an error instead of leaving the dialog on "Checking".
- Regex calls (catalog validation, restart detection) run with a match timeout.
- Elevation: CancelAsync/DisposeAsync instead of the blocking variants; implementations declare
  the interface's default CancellationToken.
- SystemProcessRunner: drop the redundant blocking WaitForExit (WaitForExitAsync already drains
  redirected output); "Restart now" launches System32\shutdown.exe by absolute path.
- ProductLinks: one home for the repository/issue/license/user-guide URLs that were duplicated
  across five files (the dead wiki link now points at the user guide).
- Smaller rule fixes (readonly fields, LINQ filters, no empty loops, nested ternaries, static
  handlers); remove the unused LegalGateViewModel.TermsVersion.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-21 19:56:27 +07:00
poli0981andClaude Opus 5.5 1f89545e30 build: central package management, NuGet audit, SonarAnalyzer, dependency refresh
- Directory.Packages.props: Central Package Management for every project; SonarAnalyzer.CSharp
  as a global analyzer so the build enforces the same rules as SonarCloud.
- Directory.Build.props: NuGet audit of direct + transitive packages (moderate+ advisories fail the
  build), deterministic CI paths, dev version 2.0.0.
- global.json: .NET SDK 10.0.402 (latest LTS feature band).
- Bumps: Microsoft.Extensions.* 10.0.13, Serilog 4.4.0, Velopack 1.2.161, CsWin32 0.3.366,
  Microsoft.NET.Test.Sdk 18.11.0, coverlet.collector 10.1.0, xunit 2.9.3 -> xunit.v3 4.0.2 (VSTest
  mode) + xunit.runner.visualstudio 4.0.1.
- The Elevator publish now inherits PublishReadyToRun from the app publish.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-21 19:56:18 +07:00
poli0981 e2f001baf7 Merge pull request #47 from poli0981/claude/multiple-windows-app-launch-530c62
fix(wpf): enforce single instance (relaunch focuses existing window)
2026-07-09 09:03:01 +07:00
poli0981andClaude Opus 4.8 c65a5aa021 fix(wpf): enforce single instance so relaunching focuses the existing window
Launching CommandForge.Wpf.exe repeatedly opened a new window each time
because there was no single-instance guard. Add SingleInstanceGuard (a
WPF-free Infrastructure primitive) that owns a session-scoped named mutex;
a later launch signals the primary via a named auto-reset event and exits,
and the primary restores + foregrounds its existing window.

- Guard is created right after VelopackApp.Build().Run() so install/update
  hook processes are never counted as a second instance.
- Activation marshals to the UI dispatcher; SetForegroundWindow beats the
  Windows foreground lock. MainWindow is NoResize so Normal fully restores it.
- Adds unit tests for primary/secondary detection, activation signalling and
  name reclamation; CHANGELOG updated for 1.5.1.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-09 08:55:52 +07:00
poli0981 4d9e70e599 Merge pull request #46 from poli0981/claude/admin-commands-windows-diag-8c26c5
feat(catalog): +40 rare/OS-specific commands & fix TPM/Defender elevation (v1.5.0)
2026-07-08 19:58:53 +07:00
poli0981andClaude Opus 4.8 ca82bae016 docs(changelog): add 1.5.0 release notes (40 commands + 2 elevation fixes)
Also backfills the missing [1.4.0] compare link and re-points [Unreleased].

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-08 19:53:31 +07:00
poli0981andClaude Opus 4.8 c424a400f6 feat(catalog): add 40 rare/OS-specific commands + fix TPM/Defender elevation (201 -> 241)
Adds 40 rarely-used and Windows-version-specific commands across 9 existing
categories: 5 Windows 10-only (maxOsBuild 19045 — the first use of maxOsBuild
gating in the catalog), 11 Windows 11-only (minOsBuild 22000+, incl. 3 for
24H2/26100), and 24 rare cross-version diagnostics/info/security/dev commands.
Each command is wired with Cmd_<id>_Title/_Desc keys in all five resource
cultures (en, vi, ja, zh-Hans, es); reg-based HKCU tweaks include
affectedRegistryValues and confirmBeforeRun for Caution entries.

Also fixes TPM Status (info.tpm) and Defender Exclusions
(sec.defender.exclusions): both now require admin so their queries
(Get-CimInstance on MicrosoftTpm / Get-MpPreference) return data instead of
appearing blank — they run in-process without elevation today.

Adds CommandDefinitionTests coverage for maxOsBuild gating (Win10-only
commands hidden on Windows 11, visible on Windows 10).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-08 19:53:13 +07:00
poli0981 c972606014 Merge pull request #45 from poli0981/claude/v1.4.0-batch1
feat(catalog): v1.4.0 — 60 new commands + Services & Startup category (141 → 201)
2026-06-29 21:00:48 +07:00
poli0981andClaude Opus 4.8 b80842a77c docs(changelog): add 1.4.0 release notes (60 commands + Services & Startup)
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-29 20:42:47 +07:00
poli0981andClaude Opus 4.8 b4bc97eb97 feat(catalog): add 20 security/updates/tweaks commands — v1.4.0 batch 3/3 (181 -> 201)
Highest-scrutiny batch: contains the only Dangerous command and all reversible
registry pairs.

- security-privacy (6): Defender threat history, Defender exclusions, BitLocker
  volume details, reset firewall to defaults (Dangerous, confirm + restore
  point), remove dynamic signatures, open Windows Security
- updates-packages (6): update history, Windows Update settings, update App
  Installer, export installed packages, third-party drivers, troubleshooters
- tweaks-shortcuts (6, 3 reversible pairs): hide/show taskbar search (Win11),
  disable/enable transparency, disable/enable Snap assist
- developer (2): enable/disable Telnet client (DISM feature)

All keys localized across EN/VI/JA/zh-Hans/ES. Catalog now at 201 commands.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-29 20:41:51 +07:00
poli0981andClaude Opus 4.8 b9cedcc160 feat(catalog): add Services & Startup category + 20 commands — v1.4.0 batch 2/3 (161 -> 181)
New 12th category "services-startup" plus a storage/maintenance-heavy batch.

- services-startup (8, NEW category): restart Print Spooler / Windows Audio /
  Windows Update / BITS services; list running & automatic services; open
  Startup apps settings; open the Startup folder
- storage (5): largest temp files, list partitions, analyze fragmentation
  (read-only), configure Disk Cleanup (sageset), list disks & volumes (diskpart)
- cleanup (3): clear icon cache, clear recent items, clear event logs
- power (2): Power Saver plan, hibernate now
- system-maintenance (2): online disk scan (Repair-Volume -Scan), verify
  system files (sfc /verifyonly)

categories.json gains services-startup (order 12); CatalogTests category-count
assertion bumped 11 -> 12. All keys localized across EN/VI/JA/zh-Hans/ES.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-29 20:34:36 +07:00
poli0981andClaude Opus 4.8 c98dd4ded9 feat(catalog): add 20 read-only/launch commands — v1.4.0 batch 1/3 (141 -> 161)
Visibility batch: system diagnostics & info that only read state or open a
console — zero Caution/Dangerous commands, ideal smoke-test set.

- system-info (7): battery health, network adapter speed, disk health,
  page file usage, local user accounts, time zone, Windows install date
- network (6): public DNS lookup test, active TCP connections, firewall
  profiles, shared folders, show hosts file, Network Connections (ncpa.cpl)
- diagnostics (5): recent boot/shutdown events, unexpected shutdowns
  (Kernel-Power 41), recent system errors, Print Management, Certificate Manager
- storage (2): drive usage summary, disk SMART status

All keys localized across EN/VI/JA/zh-Hans/ES. Catalog stays at 11 categories.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-29 20:14:20 +07:00
poli0981 6df370ec68 Merge pull request #44 from poli0981/claude/v1.3.0-changelog
docs(changelog): add 1.3.0 release notes
2026-06-26 23:17:51 +07:00
poli0981andClaude Opus 4.8 a587db3774 docs(changelog): add 1.3.0 release notes
Promote Unreleased to [1.3.0] (2026-06-26): 25 new commands + Storage
category, Simplified Chinese and Spanish UI languages, and the fixed
non-resizable main window. Update compare links.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-26 23:17:30 +07:00
poli0981 906170f4eb Merge pull request #43 from poli0981/claude/v1.3.0-commands
feat(catalog): add 25 new commands and a Storage category
2026-06-26 23:15:50 +07:00
poli0981andClaude Opus 4.8 dfac11c964 feat(catalog): add 25 new commands and a Storage category
Grows the catalog from 116 to 141 commands and adds an 11th category,
"Storage". All new commands are vetted, fixed catalog entries (no user
interpolation); admin ones run via the Elevator. No new Dangerous commands.

New category: storage (Optimize/defrag C:, Disk Management, list volumes
and free space, open Storage settings).

Other additions across existing groups:
- system-info: TPM status, Secure Boot state, computer & OS summary.
- network: network adapters, DNS servers, internet connectivity test.
- diagnostics: startup programs, Driver Verifier, Performance Monitor,
  system health report.
- cleanup: clear crash dumps, Windows Error Reporting, DNS+ARP caches.
- power: lid-close action and monitor-timeout toggles (revert pairs).
- tweaks-shortcuts: NumLock-at-startup and verbose sign-in toggles
  (revert pairs, with affectedRegistryValues).

Localization: 51 new keys (50 command + Cat_storage) added to all five
languages (EN authored; VI/JA/zh-Hans/ES machine-translated, flagged for
native review). ResxKeyTests enforces full parity.

Tests: CatalogTests category count 10 -> 11; added guards for the Storage
category and for "Dangerous commands must confirm". 195/195 passing.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-26 23:14:56 +07:00
poli0981 a592a64058 Merge pull request #42 from poli0981/claude/v1.3.0-languages
feat(i18n): add Simplified Chinese (zh-Hans) and Spanish (es) UI languages
2026-06-26 22:59:04 +07:00
poli0981andClaude Opus 4.8 a941710b29 feat(i18n): add Simplified Chinese (zh-Hans) and Spanish (es) UI languages
Adds two new UI languages, bringing the total to five (EN/VI/JA/zh-Hans/es).
Both new translations are machine-translated and flagged for native review,
matching how Japanese was introduced.

- Strings.zh-Hans.resx + Strings.es.resx: full parity with EN (501 keys),
  built by transforming the English resx so every key is present (no fallback).
- SettingsViewModel: add 简体中文 and Español language options.
- MainWindow.xaml: add the two View > Language menu items.
- ISettingsService: document the new culture codes.
- ResxKeyTests: assert key parity across all satellite cultures
  (vi/ja/zh-Hans/es), driven by a single SatelliteCultures list.
- LocalizationManagerTests: theory asserting each satellite actually loads
  (a translated string, not an English fallback) via the live-switch path.

Translations: machine-generated; recommend native-speaker review before GA.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-26 22:58:08 +07:00
poli0981 bf10498fc0 Merge pull request #41 from poli0981/claude/v1.3.0-window-lock
feat(ui): lock main window to a fixed 1100x720 size (no resize/maximize)
2026-06-26 22:46:51 +07:00
poli0981andClaude Opus 4.8 612f191ce7 feat(ui): lock main window to a fixed 1100x720 size
The main window is now fixed and non-resizable (ResizeMode=NoResize),
removing the maximize button and resize grips. The F11 full-screen
toggle (which maximized to borderless) is removed as it conflicts with
a locked window.

- MainWindow.xaml: ResizeMode=NoResize; drop MinWidth/MinHeight; remove
  the View > Full screen menu item.
- MainWindow.xaml.cs: restore/save window position only (size and
  maximized state are fixed); remove ToggleFullScreen + F11 handler.
- KeyboardShortcutsDialog: drop the F11 row.
- ISettingsService: WindowWidth/Height/Maximized retained for config
  back-compat but no longer read or written.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-26 22:45:01 +07:00
poli0981 e084a6d636 Merge pull request #40 from poli0981/dependabot/nuget/tests/CommandForge.Tests/Microsoft.NET.Test.Sdk-18.7.0
deps: Bump Microsoft.NET.Test.Sdk from 18.6.0 to 18.7.0
2026-06-25 21:14:21 +07:00
poli0981 25e6064d38 Merge pull request #39 from poli0981/dependabot/github_actions/actions/checkout-7
ci: Bump actions/checkout from 6 to 7
2026-06-25 21:11:30 +07:00
dependabot[bot] 0ac6e067ee deps: Bump Microsoft.NET.Test.Sdk from 18.6.0 to 18.7.0
---
updated-dependencies:
- dependency-name: Microsoft.NET.Test.Sdk
  dependency-version: 18.7.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-06-24 10:25:56 +00:00
dependabot[bot] 873f1e8fea ci: Bump actions/checkout from 6 to 7
Bumps [actions/checkout](https://github.com/actions/checkout) from 6 to 7.
- [Release notes](https://github.com/actions/checkout/releases)
- [Changelog](https://github.com/actions/checkout/blob/main/CHANGELOG.md)
- [Commits](https://github.com/actions/checkout/compare/v6...v7)

---
updated-dependencies:
- dependency-name: actions/checkout
  dependency-version: '7'
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-06-24 10:23:50 +00:00
poli0981 43f94f1b65 Merge pull request #38 from poli0981/claude/release-v1.2.0
docs(changelog): release v1.2.0
2026-06-21 19:56:18 +07:00
poli0981andClaude Opus 4.8 bfc1b8c219 docs(changelog): release v1.2.0
Promote the [Unreleased] section to [1.2.0] (2026-06-21) and add its
compare link. Covers the 38 new commands, OS-build version flags and
the Japanese language.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-21 19:55:45 +07:00
poli0981 4c1be876f7 Merge pull request #37 from poli0981/claude/vnext-changelog
docs(changelog): record v-next batch (commands, version flags, Japanese)
2026-06-21 19:51:59 +07:00
poli0981andClaude Opus 4.8 fa2bc278ce docs(changelog): record 38 new commands, OS version flags, Japanese (Unreleased)
Adds an [Unreleased] entry covering the v-next batch on main (PRs #33,
#35, #36): 38 new catalog commands (78 → 116), OS-build version-aware
hiding of version-specific commands, and the new Japanese language.
No version bump — release tagging left for a separate decision.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-21 19:51:19 +07:00
poli0981 1bd91115d8 Merge pull request #36 from poli0981/claude/vnext-japanese
feat(i18n): add Japanese (JA) language
2026-06-21 19:46:47 +07:00
poli0981andClaude Opus 4.8 d9af1c5fcb feat(i18n): add Japanese (JA) language
Adds a complete Japanese satellite (Strings.ja.resx, 501 keys covering
all UI + catalog strings) and wires it into the language picker and the
View menu (日本語). Live switching works the same as EN/VI — no restart.

- ResxKeyTests now asserts every catalog + UI key resolves in EN, VI
  AND JA with no parent fallback, via a shared AssertKeysExist helper.
- ISettingsService doc notes "ja" as a valid culture code.

Translations are machine-generated; a native Japanese review pass is
recommended. 189 tests pass; the ja satellite assembly builds and the
app launches.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-21 19:44:59 +07:00
poli0981 dec3efaf68 Merge pull request #35 from poli0981/claude/vnext-version-flags
feat(catalog): OS-build version flags (hide non-applicable commands)
2026-06-21 19:32:00 +07:00
poli0981 1732f9371c Merge pull request #33 from poli0981/claude/vnext-catalog-commands
feat(catalog): add 38 new commands (78 → 116)
2026-06-21 19:11:25 +07:00
poli0981andClaude Opus 4.8 ee90b5b746 feat(catalog): OS-build version flags to hide non-applicable commands
Adds optional minOsBuild/maxOsBuild to a command; the WPF catalog
projection hides commands that do not apply to the current OS build, so
Windows 11-only tweaks never appear on Windows 10 (and vice-versa).

- Domain: CommandDefinition gains MinOsBuild/MaxOsBuild + the pure
  AppliesToOsBuild(build) predicate (no Win32 dependency).
- Infrastructure: CommandDto maps the fields; CatalogLoader validates
  positive values and maxOsBuild >= minOsBuild. ICatalogProvider still
  returns the full set, so the Debug panel and tests are unaffected.
- WPF: CatalogViewModelBuilder.Build(catalog, osBuild) filters once,
  centrally — covering the list, palette, category counts and every
  dashboard. The OS build comes from the existing ISystemInfoService.
- Catalog: gate the Win11 context-menu, taskbar-alignment and
  clock-seconds tweaks (minOsBuild 22000 / 22621).

Tests: AppliesToOsBuild theory + catalog range/positive validation;
189 pass. App launches without startup regressions.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-21 19:07:54 +07:00
poli0981andClaude Opus 4.8 200645e623 feat(catalog): add 38 new commands across all 10 categories (78 → 116)
Adds 38 vetted, embedded commands spanning system-info, network,
tweaks, cleanup, power, diagnostics, updates, security and developer
groups — e.g. installed updates/drivers/BIOS/apps/monitors,
netstat/arp/route/wifi/proxy, dark-mode + Win11 taskbar/clock tweaks,
thumbnail/font/prefetch cleanup, balanced plan + power requests +
fast-startup toggle, Task/Device/Services consoles + gpresult, winget
sources + Store reset, Defender status/full-scan, firewall on/off,
WSL shutdown, Sandbox off, long-paths toggle.

- Reversible tweaks wired as set↔revert pairs; dev.sandbox.on now links
  to the new dev.sandbox.off.
- EN + VI resource keys added for every command (ResxKeyTests enforces
  both with no fallback).
- Win11-only tweaks (taskbar*, clockseconds*) ship ungated here; the
  OS-build version-flag mechanism follows in a separate change.

All 167 tests pass.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-21 18:58:07 +07:00
poli0981 52aad7d7ff Merge pull request #32 from poli0981/claude/changelog
docs: add public CHANGELOG.md
2026-06-19 16:41:37 +07:00
poli0981andClaude Opus 4.8 279aa3a24c docs: add public CHANGELOG.md (v1.0.0, v1.1.0, v1.1.1)
Adds a Keep a Changelog / SemVer changelog at the repo root covering the
initial release and the v-next feature line, and links it from the README
documentation table. (The detailed working notes in docs/ stay internal.)

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-19 16:40:51 +07:00
poli0981 de3ed23687 Merge pull request #31 from poli0981/claude/vnext-fixes
fix: cmd user-command hang + recipe dupes + sidebar scrollbar
2026-06-19 16:33:16 +07:00
poli0981andClaude Opus 4.8 68e62f3f22 fix: cmd user-commands hang, recipe duplicate steps, sidebar scrollbar
Post-v1.1.0 fixes reported from testing.

- User commands hanging on cmd: SystemProcessRunner now redirects and
  immediately closes stdin, so an interactive process (e.g. "cmd" with
  no /c) gets EOF and exits instead of blocking forever. Additionally,
  UserCommandFactory.NormalizeArguments prepends /c for cmd (e.g. "cmd"
  + "ping google.com" -> "cmd /c ping google.com") so the command runs
  and exits; the run confirmation shows the effective command line.
  PowerShell and other executables are unchanged.
- Recipes: AddStep no longer adds a command already in the chain, so a
  recipe never runs one command multiple times.
- Sidebar: hide the vertical scrollbar on the command-groups list.
- Tests for the cmd /c normalization (cmd/cmd.exe/path, existing /c|/k,
  powershell, empty args) + ToDefinition applying it.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-19 16:30:27 +07:00
304 changed files with 32514 additions and 5050 deletions

No files matched your search

+20
View File
@@ -0,0 +1,20 @@
{
"version": 1,
"isRoot": true,
"tools": {
"vpk": {
"version": "1.2.161",
"commands": [
"vpk"
],
"rollForward": false
},
"cyclonedx": {
"version": "6.3.2",
"commands": [
"dotnet-CycloneDX"
],
"rollForward": false
}
}
}
+70
View File
@@ -32,3 +32,73 @@ indent_size = 2
# Generated files: relax style enforcement
[*.{g,g.i,Designer}.cs]
generated_code = true
# --- ReSharper inspections: what Qodana reads (qodana.yaml, .gitea/workflows/qodana.yml) ---
# Qodana for .NET runs ReSharper's engine, and the engine reads these keys; so does Rider or ReSharper in the editor,
# which is why they are here and not in qodana.yaml: the same list everywhere. An inspection is off only where it
# argues with a choice this project made; each line says which. Everything else it reports is fixed. (What is NOT
# ReSharper's - a whole severity, the IntelliJ platform's inspections, JetBrains' security rules, a file the engine
# itself misreads - is in qodana.yaml.)
[*.{cs,xaml}]
# A code-behind class names its base so that the type reads whole without the half XAML generates.
resharper_redundant_extends_list_entry_highlighting = none
# An argument that repeats a default says which value the call relies on (updateAccent: true, Mica, Hide(None)).
resharper_redundant_argument_default_value_highlighting = none
# `partial void OnXChanged(T value)`: the signature is CommunityToolkit.Mvvm's generator's, used or not.
resharper_unused_parameter_in_partial_method_highlighting = none
# WPF UI's implicit styles (BasedOn {x:Type ui:Button}, ui:Card) arrive with ui:ControlsDictionary at run time, from
# a package's compiled resources the inspection does not read. A key that does not exist fails as the page loads.
resharper_xaml_static_resource_not_resolved_highlighting = none
# Pages get their DataContext in code (ShellPageProvider) and item templates bind to view-models the XAML does not
# declare, so the engine cannot resolve those bindings; it would ask for design-time types on every page. The
# accessibility tests check what the bindings must provide (names for every control and list item).
resharper_xaml_binding_with_context_not_resolved_highlighting = none
# Proposals, not findings - ReSharper's suggestions for a style this project did not take. Its style is this file,
# `dotnet format` and the analyzers the build treats as errors (SonarAnalyzer included).
resharper_convert_to_primary_constructor_highlighting = none
resharper_merge_into_pattern_highlighting = none
resharper_use_utf8_string_literal_highlighting = none
resharper_arrange_object_creation_when_type_evident_highlighting = none
resharper_convert_closure_to_method_group_highlighting = none
resharper_use_collection_expression_highlighting = none
resharper_convert_to_auto_property_highlighting = none
# The streams and pipes these name are closed synchronously on purpose; `await using` would add a ConfigureAwait to
# every one without closing them any sooner.
resharper_use_await_using_highlighting = none
# A member's accessibility is what its type offers, not a count of today's callers.
resharper_member_can_be_private_global_highlighting = none
resharper_property_can_be_made_init_only_global_highlighting = none
resharper_auto_property_can_be_made_get_only_global_highlighting = none
# "Never used" across the solution is not what decides for a member other code can reach: a view-model's properties
# and commands are read by XAML bindings the engine cannot resolve (above), the product links by x:Static, and a
# model's members by System.Text.Json. The private kind (.Local) stays on.
resharper_unused_member_global_highlighting = none
resharper_unused_auto_property_accessor_global_highlighting = none
resharper_unused_method_return_value_global_highlighting = none
resharper_unused_parameter_global_highlighting = none
resharper_class_never_instantiated_global_highlighting = none
resharper_event_never_subscribed_to_global_highlighting = none
resharper_collection_never_queried_global_highlighting = none
# The compiler's nullable analysis is the gate (warnings are errors). These three go further and call a guard
# redundant because an annotation promises non-null - where a JSON file read from disk, a dependency property or a
# WPF event hands over null all the same (the corrupt-file tests rely on those guards).
resharper_null_coalescing_condition_is_always_not_null_according_to_api_contract_highlighting = none
resharper_conditional_access_qualifier_is_non_nullable_according_to_api_contract_highlighting = none
resharper_condition_is_always_true_or_false_according_to_nullable_api_contract_highlighting = none
# A record's positional property is part of its equality and of what it prints, and XAML binds to it by name.
resharper_not_accessed_positional_property_global_highlighting = none
resharper_not_accessed_positional_property_local_highlighting = none
# `default: break;` is how a switch says the rest is left alone on purpose (and Sonar S131 asks for the default).
resharper_redundant_empty_switch_section_highlighting = none
# Async void only for event handlers (CLAUDE.md), which is what these are.
resharper_async_void_event_handler_method_highlighting = none
[*.resx]
# A vi, ja, zh-Hans or es value that equals the English one is deliberate: product, tool and command names (winget,
# DISM, SFC), units and format strings are not translated.
resharper_overridden_with_same_value_highlighting = none
[tests/**/*.cs]
# A test's lambda runs inside the `using` scope it captures from, and reads a variable the test changes on purpose.
resharper_access_to_disposed_closure_highlighting = none
resharper_access_to_modified_closure_highlighting = none
+37
View File
@@ -0,0 +1,37 @@
name: Announce Release
# Posts a release to Discord through the ops repo's announce-release.yml (which reads the release
# from the Gitea API).
#
# Tag releases are announced by release.yml itself: a release created with the job token fires no
# `release` event (Gitea credits it to its Actions user, whose events start nothing). This workflow
# covers a release a person publishes in the UI, and re-runs: Actions → Announce Release → Run
# workflow, with the tag.
# Secrets: DISCORD_RELEASES_WEBHOOK (or DISCORD_REPO_WEBHOOK); optional DISCORD_PING_ROLE_ID.
on:
release:
types: [published]
workflow_dispatch:
inputs:
tag:
description: Release tag to announce (e.g. v2.3.0)
required: true
type: string
permissions:
contents: read
jobs:
announce:
permissions:
contents: read
uses: poli0981/.github/.gitea/workflows/announce-release.yml@c133a00dc7a0bd7bd68253d415758b408d615fa4 # ops v2026.11.4
with:
tag_override: ${{ inputs.tag || '' }}
ops_ref: c133a00dc7a0bd7bd68253d415758b408d615fa4
# Only what the shared workflow declares, not `inherit`.
secrets:
DISCORD_RELEASES_WEBHOOK: ${{ secrets.DISCORD_RELEASES_WEBHOOK }}
DISCORD_REPO_WEBHOOK: ${{ secrets.DISCORD_REPO_WEBHOOK }}
DISCORD_PING_ROLE_ID: ${{ secrets.DISCORD_PING_ROLE_ID }}
+110
View File
@@ -0,0 +1,110 @@
name: Build
# Build, format check, tests and a packaging smoke test on every push to main and every pull
# request (Gitea Actions, ops runbook poli0981/.github docs/GITEA-MIGRATION.md).
#
# - `windows-latest` is HOST MODE on the maintainer's PC (PowerShell, no isolation): setup-dotnet
# installs into the runner tool cache (DOTNET_INSTALL_DIR), never into C:\Program Files. NuGet
# packages come from the PC's per-user cache, which outlives the job, so there is no actions/cache.
# - Upstream actions/upload-artifact v4+ refuses non-GitHub servers: the Gitea fork uploads.
# - Outsiders cannot open pull requests on Gitea (registration is off), so no run here comes from
# a stranger's fork.
on:
push:
branches: [main]
pull_request:
branches: [main]
workflow_dispatch:
permissions:
contents: read
concurrency:
group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }}
cancel-in-progress: ${{ github.event_name == 'pull_request' }}
env:
DOTNET_NOLOGO: true
DOTNET_CLI_TELEMETRY_OPTOUT: true
jobs:
build:
# WPF (net10.0-windows) only builds on Windows.
runs-on: windows-latest
timeout-minutes: 30
permissions:
contents: read
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
- name: Keep .NET SDK installs in the runner tool cache (host mode)
shell: pwsh
run: |
$base = if ($env:RUNNER_TOOL_CACHE) { $env:RUNNER_TOOL_CACHE } else { Join-Path $env:LOCALAPPDATA 'gitea-runner\toolcache' }
"DOTNET_INSTALL_DIR=$(Join-Path $base 'dotnet')" >> $env:GITHUB_ENV
- uses: actions/setup-dotnet@0f4a354dd5547a28c70b7853dbd95d5b67886e73 # v6.1.0
with:
global-json-file: global.json
- name: Restore (NuGet audit fails on moderate+ advisories)
run: dotnet restore CommandForge.slnx
- name: Verify formatting
run: dotnet format CommandForge.slnx --verify-no-changes --no-restore
- name: Build (Release, warnings = errors)
run: dotnet build CommandForge.slnx -c Release --no-restore
- name: Test
run: >-
dotnet test CommandForge.slnx -c Release --no-build
--logger "trx;LogFileName=test-results.trx"
--collect "XPlat Code Coverage"
--results-directory TestResults
- name: Upload test results
if: ${{ !cancelled() }}
uses: christopherhx/gitea-upload-artifact@81f940d004763f986ba3582c007fd842dd5cb0d7 # v4
with:
name: test-results
path: TestResults
if-no-files-found: ignore
retention-days: 14
package:
# Publishes and packs exactly like release.yml, so a packaging regression (e.g. the Elevator
# missing from the publish folder) fails the pull request instead of the tagged release.
runs-on: windows-latest
timeout-minutes: 30
permissions:
contents: read
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
- name: Keep .NET SDK installs in the runner tool cache (host mode)
shell: pwsh
run: |
$base = if ($env:RUNNER_TOOL_CACHE) { $env:RUNNER_TOOL_CACHE } else { Join-Path $env:LOCALAPPDATA 'gitea-runner\toolcache' }
"DOTNET_INSTALL_DIR=$(Join-Path $base 'dotnet')" >> $env:GITHUB_ENV
- uses: actions/setup-dotnet@0f4a354dd5547a28c70b7853dbd95d5b67886e73 # v6.1.0
with:
global-json-file: global.json
- name: Publish + pack (Velopack smoke test)
shell: pwsh
run: ./scripts/pack.ps1 -Version 0.0.1
- name: Upload installer preview
uses: christopherhx/gitea-upload-artifact@81f940d004763f986ba3582c007fd842dd5cb0d7 # v4
with:
name: installer-preview
path: Releases/*-Setup.exe
if-no-files-found: error
retention-days: 7
+28
View File
@@ -0,0 +1,28 @@
name: Notify CI Failure
# A failed run of the workflows below on main posts to Discord through the ops repo's
# notify-ci-failure.yml (its script is loaded at `ops_ref`, the same commit as `uses:`). Neither file
# checks out the triggering run's code: they read run metadata only, and the shared workflow passes
# every untrusted field to the notifier through `env:`. Pull-request runs are skipped there (it only
# reports the default branch). Requires the repository secret DISCORD_CI_WEBHOOK.
on:
workflow_run:
workflows: ["Build", "Qodana", "Security"]
types: [completed]
permissions:
contents: read
actions: read
jobs:
notify:
permissions:
contents: read
actions: read
uses: poli0981/.github/.gitea/workflows/notify-ci-failure.yml@c133a00dc7a0bd7bd68253d415758b408d615fa4 # ops v2026.11.4
with:
default_branch: main
ops_ref: c133a00dc7a0bd7bd68253d415758b408d615fa4
secrets:
DISCORD_CI_WEBHOOK: ${{ secrets.DISCORD_CI_WEBHOOK }}
@@ -0,0 +1,26 @@
name: Notify Release Pipeline
# Every finished run of release.yml (success, failure or cancelled) is reported to Discord through
# the ops repo's notify-release-pipeline.yml. It matches the producer by its exact `name:`, so
# renaming release.yml's `name: Release` silently breaks this filter.
# Requires the repository secret DISCORD_RELEASE_PIPELINE_WEBHOOK.
on:
workflow_run:
workflows: ["Release"]
types: [completed]
permissions:
contents: read
actions: read
jobs:
notify:
permissions:
contents: read
actions: read
uses: poli0981/.github/.gitea/workflows/notify-release-pipeline.yml@c133a00dc7a0bd7bd68253d415758b408d615fa4 # ops v2026.11.4
with:
ops_ref: c133a00dc7a0bd7bd68253d415758b408d615fa4
secrets:
DISCORD_RELEASE_PIPELINE_WEBHOOK: ${{ secrets.DISCORD_RELEASE_PIPELINE_WEBHOOK }}
+46
View File
@@ -0,0 +1,46 @@
name: Qodana
# JetBrains Qodana for .NET (`qodana-dotnet`, Rider's engine, on the Ultimate licence of the Qodana
# Cloud project): ReSharper's C#, XAML and .resx inspections, the IntelliJ platform's Markdown and
# XML inspections and JetBrains' security rules, over the whole solution. Every setting is in
# qodana.yaml; the gate there is zero problems.
#
# Runs the Qodana CLI through the ops repo's reusable-qodana.yml (JetBrains/qodana-action needs
# GitHub's APIs). Gitea has no code-scanning UI: the results go to Qodana Cloud and to the run's
# `qodana-report` artifact (SARIF and the linter's logs, for a reader without a Qodana Cloud account).
#
# - Native mode on `windows-latest` (host mode on the maintainer's PC): WPF (net10.0-windows) only
# loads on Windows, and the linter reads the projects with the SDK global.json names.
# - The solution is built first (prepare-command), so a build that fails is one red step with the
# compiler's own message rather than a report of unresolved symbols.
# - Advisory: not a required check of `main`, so a finding, a Qodana Cloud outage or a lapsed licence
# is a red job beside a green build, never a blocked merge. Runs started by renovate-bot skip it
# (the reusable's rule: a same-repo pull request gets the repository's secrets).
# Requires the repository secret QODANA_TOKEN.
on:
push:
branches: [main]
pull_request:
branches: [main]
workflow_dispatch:
permissions:
contents: read
concurrency:
group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }}
cancel-in-progress: ${{ github.event_name == 'pull_request' }}
jobs:
qodana:
permissions:
contents: read
uses: poli0981/.github/.gitea/workflows/reusable-qodana.yml@c133a00dc7a0bd7bd68253d415758b408d615fa4 # ops v2026.11.4
with:
runs-on: windows-latest
dotnet-global-json-file: global.json
prepare-command: dotnet build CommandForge.slnx -c Release
artifact-name: qodana-report
secrets:
QODANA_TOKEN: ${{ secrets.QODANA_TOKEN }}
+235
View File
@@ -0,0 +1,235 @@
name: Release
# A signed `vX.Y.Z` tag on main releases CommandForge (RELEASING.md; ops runbook §3.3 and §5.1):
#
# build publish + Velopack pack (scripts/pack.ps1) on the maintainer's PC (host mode), the
# CycloneDX SBOM, SHA256SUMS and the release notes (scripts/release-assets.ps1), an
# optional VirusTotal scan, then `vpk upload s3` to Cloudflare R2: packages first, the
# feed (releases.win.json) last, so a client never sees a feed whose files are missing.
# Installed copies (2.3.0 and later) update from https://releases.poli0981.dev/commandforge.
# publish the ops repo's publish-r2.yml puts SHA256SUMS and the SBOM under <version>/.
# release a Gitea release with the notes and the links (no binaries: the forge's disk is not for
# them, runbook §1).
# announce Discord, through the ops repo's announce-release.yml: a release made with the job
# token fires no `release` event, so announce-release.yml would never run by itself.
#
# Manual run (Actions → Release → Run workflow) on a branch is a DRY RUN: it builds, packs, writes
# the SBOM/checksums/notes from <Version> in Directory.Build.props, and reads the previous release
# from R2 (a check of the R2 credentials), but uploads nothing; the files stay as the `r2-release`
# artifact. Uploads, the release and the announcement happen only for a `v*` tag. A file uploaded
# under a versioned name is never replaced: to ship a fix, bump the version.
#
# Release credentials (user-level secrets R2_RELEASES_ACCESS_KEY_ID / _SECRET_ACCESS_KEY, variable
# R2_ACCOUNT_ID) exist only in steps of this tag/dispatch-only workflow (runbook §2 rule 10), as VPK_*
# environment variables, never on a command line. Optional repository secret VT_API_KEY turns on
# the VirusTotal scan. No dependency caches: a poisoned cache could end up inside the installer.
# No code signing yet (SECURITY.md), no build-provenance attestations (no OIDC on Gitea, D7).
on:
push:
tags: ['v*']
workflow_dispatch:
permissions:
contents: read
concurrency:
group: release
cancel-in-progress: false
env:
DOTNET_NOLOGO: true
DOTNET_CLI_TELEMETRY_OPTOUT: true
jobs:
build:
name: Build, pack and upload to R2
runs-on: windows-latest # host mode on the maintainer's PC (PowerShell)
timeout-minutes: 60
permissions:
contents: read
outputs:
version: ${{ steps.ver.outputs.version }}
env:
IS_TAG: ${{ startsWith(github.ref, 'refs/tags/v') }}
# Velopack's S3 options (vpk reads VPK_<OPTION>): bucket poli0981-releases, folder commandforge/
VPK_BUCKET: poli0981-releases
VPK_PREFIX: commandforge/
VPK_ENDPOINT: https://${{ vars.R2_ACCOUNT_ID }}.r2.cloudflarestorage.com
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
- name: Keep .NET SDK installs in the runner tool cache (host mode)
shell: pwsh
run: |
$base = if ($env:RUNNER_TOOL_CACHE) { $env:RUNNER_TOOL_CACHE } else { Join-Path $env:LOCALAPPDATA 'gitea-runner\toolcache' }
"DOTNET_INSTALL_DIR=$(Join-Path $base 'dotnet')" >> $env:GITHUB_ENV
- uses: actions/setup-dotnet@0f4a354dd5547a28c70b7853dbd95d5b67886e73 # v6.1.0
with:
global-json-file: global.json
# A tag must name the version Directory.Build.props carries (the release commit sets both).
- name: Resolve the version
id: ver
shell: pwsh
env:
REF_NAME: ${{ github.ref_name }}
R2_ACCOUNT_ID: ${{ vars.R2_ACCOUNT_ID }}
run: |
function Fail([string]$msg) { Write-Host "::error::$msg"; exit 1 }
$props = "$(dotnet msbuild src/CommandForge.Domain/CommandForge.Domain.csproj -getProperty:Version | Select-Object -Last 1)".Trim()
if ($LASTEXITCODE -ne 0 -or $props -notmatch '^\d+\.\d+\.\d+$') { Fail "Unexpected <Version> '$props' in Directory.Build.props" }
if ($env:IS_TAG -eq 'true') {
$version = $env:REF_NAME -replace '^v', ''
if ($version -ne $props) { Fail "Tag $($env:REF_NAME) does not match <Version> $props in Directory.Build.props" }
} else {
$version = $props
Write-Host "::notice::Dry run on $($env:REF_NAME): builds $version, uploads nothing."
}
if ($env:R2_ACCOUNT_ID -notmatch '^[0-9a-f]{32}$') { Fail 'Actions variable R2_ACCOUNT_ID is missing or not a 32-hex Cloudflare account ID' }
"version=$version" >> $env:GITHUB_OUTPUT
Write-Host "Releasing CommandForge $version"
- name: Restore pinned tools (vpk, CycloneDX)
run: dotnet tool restore
# The previous release, so vpk can build a delta package. Nothing to find before the first
# release on R2 (2.3.0): the step then fails and the job goes on.
- name: Download the previous release from R2
continue-on-error: true
shell: pwsh
env:
VPK_KEY_ID: ${{ secrets.R2_RELEASES_ACCESS_KEY_ID }}
VPK_SECRET: ${{ secrets.R2_RELEASES_SECRET_ACCESS_KEY }}
run: |
dotnet vpk download s3 --channel win --outputDir Releases
exit $LASTEXITCODE
- name: Publish + pack (Velopack)
shell: pwsh
env:
VERSION: ${{ steps.ver.outputs.version }}
run: ./scripts/pack.ps1 -Version $env:VERSION
# A step's own env is not visible to its `if:`, so a step of its own looks for the key.
- name: Look for VT_API_KEY
id: vtkey
shell: pwsh
env:
VT_API_KEY: ${{ secrets.VT_API_KEY }}
run: |
"available=$(if ($env:VT_API_KEY) { 'true' } else { 'false' })" >> $env:GITHUB_OUTPUT
- name: VirusTotal scan (optional)
id: vt
if: ${{ env.IS_TAG == 'true' && steps.vtkey.outputs.available == 'true' }}
uses: crazy-max/ghaction-virustotal@936d8c5c00afe97d3d9a1af26d017cfdf26800a2 # v5.0.0
with:
vt_api_key: ${{ secrets.VT_API_KEY }}
files: |
Releases/CommandForge-win-Setup.exe
Releases/CommandForge-${{ steps.ver.outputs.version }}-full.nupkg
- name: SBOM, SHA256SUMS and release notes
shell: pwsh
env:
VERSION: ${{ steps.ver.outputs.version }}
VT_ANALYSIS: ${{ steps.vt.outputs.analysis }}
run: ./scripts/release-assets.ps1 -Version $env:VERSION -VirusTotalAnalysis "$env:VT_ANALYSIS"
# vpk uploads the packages, the installer and the portable zip first and the feed last, and
# keeps the 10 newest releases in the feed folder (the only deletion CI does, runbook §3.3).
# Should R2 refuse the AWS SDK's default checksums, the upload is tried once more with
# --disableChecksumValidation, and the log says so.
- name: Upload to R2 (Velopack)
if: ${{ env.IS_TAG == 'true' }}
shell: pwsh
env:
VPK_KEY_ID: ${{ secrets.R2_RELEASES_ACCESS_KEY_ID }}
VPK_SECRET: ${{ secrets.R2_RELEASES_SECRET_ACCESS_KEY }}
run: |
dotnet vpk upload s3 --channel win --outputDir Releases --keepMaxReleases 10
if ($LASTEXITCODE -ne 0) {
Write-Host '::warning::vpk upload s3 failed; trying once more with --disableChecksumValidation'
dotnet vpk upload s3 --channel win --outputDir Releases --keepMaxReleases 10 --disableChecksumValidation
}
exit $LASTEXITCODE
- name: Smoke test the public files
if: ${{ env.IS_TAG == 'true' }}
shell: pwsh
env:
VERSION: ${{ steps.ver.outputs.version }}
run: |
$base = 'https://releases.poli0981.dev/commandforge'
foreach ($name in 'releases.win.json', 'CommandForge-win-Setup.exe', 'CommandForge-win-Portable.zip', "CommandForge-$($env:VERSION)-full.nupkg") {
$code = curl.exe -sS -o NUL -I -w '%{http_code}' --retry 3 --retry-all-errors "$base/$name"
Write-Host "HEAD $base/$name -> $code"
if ($code -ne '200') { Write-Host "::error::Not reachable after upload: $base/$name"; exit 1 }
}
$feed = curl.exe -fsS --retry 3 "$base/releases.win.json" | ConvertFrom-Json
if (-not ($feed.Assets | Where-Object { $_.Version -eq $env:VERSION })) { Write-Host "::error::releases.win.json does not list $($env:VERSION)"; exit 1 }
- name: Keep the release files
uses: christopherhx/gitea-upload-artifact@81f940d004763f986ba3582c007fd842dd5cb0d7 # v4
with:
name: r2-release
path: r2-release/
if-no-files-found: error
retention-days: 7
publish:
name: SHA256SUMS and SBOM to R2
needs: build
if: ${{ startsWith(github.ref, 'refs/tags/v') }}
permissions:
contents: read
uses: poli0981/.github/.gitea/workflows/publish-r2.yml@c133a00dc7a0bd7bd68253d415758b408d615fa4 # ops v2026.11.4
with:
app: commandforge
artifact: r2-release
versioned-dir: versioned # versioned/2.3.0/SHA256SUMS → commandforge/2.3.0/SHA256SUMS
runs-on: ubuntu-latest
secrets:
R2_RELEASES_ACCESS_KEY_ID: ${{ secrets.R2_RELEASES_ACCESS_KEY_ID }}
R2_RELEASES_SECRET_ACCESS_KEY: ${{ secrets.R2_RELEASES_SECRET_ACCESS_KEY }}
release:
name: Gitea release (notes + links)
needs: [build, publish]
if: ${{ startsWith(github.ref, 'refs/tags/v') }}
runs-on: ubuntu-latest
timeout-minutes: 10
permissions:
contents: write # which of contents / releases Gitea enforces is unverified (runbook §3.2 item 5)
releases: write
steps:
- name: Download the release files
uses: christopherhx/gitea-download-artifact@75635f32b4c1c41c4b3d64e8f85210112ed4c9c7 # v4
with:
name: r2-release
path: r2-release
- name: Create the release
uses: https://gitea.com/actions/gitea-release-action@5a83c90484ef4355121df5eb60558c8ce66e81ac # v1.3.7
with:
tag_name: ${{ github.ref_name }}
name: CommandForge ${{ needs.build.outputs.version }}
body_path: r2-release/release-notes.md
announce:
needs: release
if: ${{ startsWith(github.ref, 'refs/tags/v') }}
permissions:
contents: read
uses: poli0981/.github/.gitea/workflows/announce-release.yml@c133a00dc7a0bd7bd68253d415758b408d615fa4 # ops v2026.11.4
with:
tag_override: ${{ github.ref_name }}
ops_ref: c133a00dc7a0bd7bd68253d415758b408d615fa4
secrets:
DISCORD_RELEASES_WEBHOOK: ${{ secrets.DISCORD_RELEASES_WEBHOOK }}
DISCORD_REPO_WEBHOOK: ${{ secrets.DISCORD_REPO_WEBHOOK }}
DISCORD_PING_ROLE_ID: ${{ secrets.DISCORD_PING_ROLE_ID }}
+82
View File
@@ -0,0 +1,82 @@
name: Security
# Gitea has no CodeQL, no dependency review and no code-scanning UI (ops runbook §1, migration
# decision D7). This workflow covers instead:
#
# workflow-lint actionlint + shellcheck on .gitea/workflows/*.yml (CodeQL's `actions` analysis
# is gone; Opengrep's GitHub Actions rules below also check for injection)
# scan the ops repo's security.yml: gitleaks (full history), Opengrep (SAST, report
# only), osv-scanner (lockfiles; this repo has none, so it has nothing to scan)
# and a `dotnet restore` with NuGetAudit that fails on high/critical advisories
# (NU1903/NU1904). build.yml's restore already fails on moderate ones.
#
# Weekly as well, so a new advisory against unchanged dependencies turns it red: Friday 14:11 UTC
# = 21:11 Vietnam (a free slot in the ops repo's cron registry; the runner is the maintainer's PC
# and only runs 13:00–16:00 UTC).
on:
push:
branches: [main]
pull_request:
branches: [main]
schedule:
- cron: '11 14 * * 5'
workflow_dispatch:
permissions:
contents: read
concurrency:
group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }}
cancel-in-progress: ${{ github.event_name == 'pull_request' }}
jobs:
# Both linters as release binaries at pinned versions, SHA-256 verified (the pins of the ops
# repo's ops-lint.yml). Renovate does not update them: bump version and checksum together.
workflow-lint:
runs-on: ubuntu-latest
timeout-minutes: 10
permissions:
contents: read
env:
ACTIONLINT_VERSION: 1.7.12
ACTIONLINT_SHA256: 8aca8db96f1b94770f1b0d72b6dddcb1ebb8123cb3712530b08cc387b349a3d8 # actionlint_1.7.12_linux_amd64.tar.gz
SHELLCHECK_VERSION: v0.11.0
SHELLCHECK_SHA256: 8c3be12b05d5c177a04c29e3c78ce89ac86f1595681cab149b65b97c4e227198 # shellcheck-v0.11.0.linux.x86_64.tar.xz
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
- name: Install actionlint ${{ env.ACTIONLINT_VERSION }} + shellcheck ${{ env.SHELLCHECK_VERSION }}
run: |
set -euo pipefail
tmp="${RUNNER_TEMP:-/tmp}"
bin="$tmp/lint-bin"
mkdir -p "$bin"
curl -fsSL --retry 3 -o "$tmp/actionlint.tar.gz" \
"https://github.com/rhysd/actionlint/releases/download/v${ACTIONLINT_VERSION}/actionlint_${ACTIONLINT_VERSION}_linux_amd64.tar.gz"
echo "${ACTIONLINT_SHA256} $tmp/actionlint.tar.gz" | sha256sum -c -
tar -xzf "$tmp/actionlint.tar.gz" -C "$bin" actionlint
curl -fsSL --retry 3 -o "$tmp/shellcheck.tar.xz" \
"https://github.com/koalaman/shellcheck/releases/download/${SHELLCHECK_VERSION}/shellcheck-${SHELLCHECK_VERSION}.linux.x86_64.tar.xz"
echo "${SHELLCHECK_SHA256} $tmp/shellcheck.tar.xz" | sha256sum -c -
tar -xJf "$tmp/shellcheck.tar.xz" -C "$bin" --strip-components=1 "shellcheck-${SHELLCHECK_VERSION}/shellcheck"
echo "$bin" >> "$GITHUB_PATH"
# The files by name: actionlint only finds .github/workflows by itself. .github/actionlint.yaml
# ignores only the Gitea features actionlint does not know; everything else stays an error.
- name: actionlint (workflow syntax and expressions)
run: |
actionlint -version
actionlint -color -config-file .github/actionlint.yaml \
-shellcheck "$(command -v shellcheck)" .gitea/workflows/*.yml
scan:
permissions:
contents: read
uses: poli0981/.github/.gitea/workflows/security.yml@c133a00dc7a0bd7bd68253d415758b408d615fa4 # ops v2026.11.4
with:
dotnet: true
dotnet-runs-on: windows-latest # WPF (net10.0-windows) restores only on Windows
dotnet-solution: CommandForge.slnx
+9 -7
View File
@@ -3,11 +3,13 @@
This project adopts the **[Contributor Covenant, version 2.1](https://www.contributor-covenant.org/version/2/1/code_of_conduct/)**.
In short: be respectful and constructive. Harassment, insults, personal attacks, and other
behavior that violates
[GitHub's Acceptable Use Policies](https://docs.github.com/site-policy/acceptable-use-policies)
are not tolerated in this project's spaces (issues, pull requests, discussions, and comments).
abusive behavior are not tolerated in this project's spaces (issues, merge requests, e-mail and
comments, on the GitLab mirror or anywhere else the project is discussed).
Please read the full text linked above. To report unacceptable behavior, contact the maintainer
via [GitHub private vulnerability reporting](https://github.com/poli0981/CommandForge/security/advisories/new)
or by opening a minimal issue asking for a private contact channel (do not include sensitive
details in a public issue).
Please read the full text linked above.
## Reporting
To report unacceptable behavior, email **[code@poli0981.dev](mailto:code@poli0981.dev)**. Reports
are handled privately; don't put sensitive details in a public issue. On the GitLab mirror you can
also use GitLab's **Report abuse** option on the comment or issue concerned.
+108 -18
View File
@@ -2,37 +2,126 @@
Thanks for your interest! CommandForge is a GPLv3, offline-first Windows tool that runs
system-level commands, so **safety and clarity matter more than speed**. Please read this before
opening an issue or pull request.
opening an issue or merge request.
## Where things live
- **Source (canonical):** [`git.poli0981.dev/poli0981/CommandForge`](https://git.poli0981.dev/poli0981/CommandForge), the maintainer's
Gitea. Its registration is closed, so it is read-only for everyone else; CI (Gitea Actions) runs
there.
- **Issues and merge requests:** the public mirror [`gitlab.com/poli0981/CommandForge`](https://gitlab.com/poli0981/CommandForge),
which Gitea keeps up to date. GitLab CI does not run on the mirror: the maintainer applies an
accepted merge request on Gitea, where CI runs, and the mirror then shows it as merged (or it is
closed with a link to the commit).
- **Patches by e-mail:** `git format-patch` / `git send-email` to
[code@poli0981.dev](mailto:code@poli0981.dev) work too.
- **Security:** [security@poli0981.dev](mailto:security@poli0981.dev) only, never a public issue
(see [SECURITY.md](SECURITY.md)).
## Maintenance mode: what we accept
**CommandForge is stable and in maintenance mode** since version 2.2.0 (November 2026). It does
what it set out to do — run vetted Windows maintenance commands from a safe, categorized window —
so the work now goes into keeping it secure, correct and accessible, not into new features.
**Still done:**
1. **Dependency updates**, regularly.
2. **Security fixes.** A High or Critical vulnerability in a dependency or in the toolchain — for
example the .NET runtime the app ships with, or Node.js, which the CI's actions run on — gets
an urgent patch release; a Moderate one goes into the next routine update. A new
feature is added only when it is genuinely necessary, for example to keep the app safe or
working on a new Windows build.
3. **Major platform updates**, such as moving to a newer .NET.
4. **Issues and pull requests** that add or remove catalog commands; fix bugs, UI/UX problems or
accessibility barriers; or fix commands that are outdated, use the wrong syntax or could be
harmful (a harmful one is reported privately, see [SECURITY.md](SECURITY.md)).
5. **Translation fixes** for English, Vietnamese, Japanese, Simplified Chinese and Spanish: wording
that doesn't suit the culture or the local tone, and spelling that could mislead.
**Not accepted:** issues and merge requests for new features, unless the feature clearly fits the
project and is genuinely necessary; others are closed with a link to this section.
## Quick start
Requires Windows 10 22H2 / 11 and the .NET 10 SDK.
```bash
dotnet restore
dotnet build -c Release # must be 0 warnings (warnings are errors)
dotnet test # all tests must pass
dotnet format # match the code style
dotnet build -c Release # must be 0 warnings (warnings are errors)
dotnet test # all tests must pass
dotnet format --verify-no-changes # match the code style (run `dotnet format` to fix)
```
See [BUILD.md](../BUILD.md) for publish/packaging.
See [BUILD.md](../BUILD.md) for packaging and CI.
## Reporting issues
- Use the issue templates (Bug report / Feature request).
- Open an [issue on the GitLab mirror](https://gitlab.com/poli0981/CommandForge/-/issues/new) and pick a template: **Bug**,
**Command**, **Translation**, **Accessibility** or **Feature request** (within the policy above).
In the app, **More → Report a bug** fills the Bug template in for you.
- **Get straight to the point**: what you expected, what happened, exact steps, your Windows
version/build and the app version (Settings → About).
version/build and the app version (**More → About** in the app).
- For **security vulnerabilities, do NOT open a public issue** — see [SECURITY.md](SECURITY.md).
- Questions: e-mail [code@poli0981.dev](mailto:code@poli0981.dev).
- An accessibility barrier can also go to
[accessibility@poli0981.dev](mailto:accessibility@poli0981.dev) — see
[ACCESSIBILITY.md](../ACCESSIBILITY.md).
## Pull requests
## Merge requests and patches
- Keep PRs **focused and small**; one logical change per PR.
- Match existing style; run `dotnet format` and keep the build at **0 warnings**.
- **Don't delete or disable tests** to make CI pass; add tests for new behavior.
- **Adding a command?** Add it to the catalog JSON (`Infrastructure/Catalog/commands.json`) per
the schema, add the EN/VI resource strings, and keep `requiresAdmin`/`dangerLevel` accurate.
Never add a code path that runs arbitrary commands or self-elevates outside the vetted catalog.
- Keep changes **focused and small**; one logical change per merge request or patch series.
- Match existing style; run `dotnet format` and keep the build at **0 warnings** (analyzers,
including SonarAnalyzer, run as part of the build).
- **Don't delete or disable tests** to make CI pass; add tests for new behavior, and put logic in
view models and helpers that tests can reach (XAML code-behind is hard to test).
- **Sign your commits** (GPG or SSH) where you can; the maintainer's commits and release tags are
signed. Commit messages follow [Conventional Commits](https://www.conventionalcommits.org/)
(`fix(catalog): …`, `feat(ui): …`).
- The maintainer runs your change through CI on Gitea before merging: `Build` (`build` and
`package`) must pass, and `Security` (gitleaks, Opengrep, osv-scanner, NuGetAudit, actionlint)
and the Qodana report (zero problems expected) are checked too.
- **Dependencies:** package versions live in each `.csproj` (not in `Directory.Packages.props`).
Discuss a new package before adding it; runtime dependencies must be GPLv3-compatible. Renovate
proposes updates on its own.
- **UI text** goes in the `.resx` files, never hardcoded, and every key needs a value in all five
languages: `Strings.resx` (English), `Strings.vi.resx`, `Strings.ja.resx`, `Strings.zh-Hans.resx`
and `Strings.es.resx`. A test fails when a key the UI uses is missing from any of them.
Machine-translated text is fine if you say so; native-speaker fixes are very welcome.
- **Accessibility:** every control that shows no text gets an `AutomationProperties.Name` from the
`.resx`; list items are named by what they show (an `ItemContainerStyle`); icons are
`ctl:DecorativeIcon`, which keeps their glyphs from screen readers; nothing is shown by colour
alone. The accessibility tests check most of this; say in the PR what you tried with the keyboard
alone and with Narrator ([ACCESSIBILITY.md](../ACCESSIBILITY.md#for-contributors)).
- **Disclose AI assistance.** AI-assisted contributions are welcome — just say so in the PR
description.
### Adding a command
Commands live only in the embedded catalog,
`src/CommandForge.Infrastructure/Catalog/commands.json`. Never add a code path that runs arbitrary
commands or elevates outside the vetted catalog.
- Give it a unique `id`, a `categoryId` from `categories.json`, and `titleKey`/`descriptionKey`
strings in all five languages.
- Keep `requiresAdmin` and `dangerLevel` accurate:
- **Safe** — no risk of losing data: read-only queries, opening a tool or settings page, or a
small preference change that is undone the same way it was made.
- **Caution** — changes system state (services, registry, caches, boot-time checks);
recoverable, but undoing it may take effort.
- **Dangerous** — may lose data, remove a rollback option or leave Windows unstable.
Caution and Dangerous commands need `"confirmBeforeRun": true`.
- `executable` is a plain program name (it is resolved to a trusted absolute path). PowerShell
commands must pass `-NoProfile -NonInteractive`.
- Use the `{SystemDrive}`, `{SystemRoot}` and `{UserProfile}` placeholders instead of hard-coded
paths or `%VARIABLES%`.
- Use `minOsBuild` / `maxOsBuild` for commands that only exist on some Windows builds, and
`revertCommandId` when another catalog command undoes this one.
- The `icon` name must be mapped in `src/CommandForge.Wpf/Converters/IconMap.cs`.
The catalog tests check these rules, and the app's loader rejects invalid records.
## AI-assisted contributions
AI tools are welcome for writing and reviewing changes **when disclosed**. What is *not*
@@ -45,12 +134,12 @@ To protect users, the following are **closed without review** and may result in
ban — no exceptions:
- **Suspected malicious code.** If a PR appears to contain a supply-chain attack, obfuscation,
credential harvesting, a cryptominer, or any malware — even if CodeQL and Dependabot don't flag
credential harvesting, a cryptominer, or any malware — even if the automated scans don't flag
it — the maintainer may investigate manually. **Detection equals a ban.**
- **Unverified or suspicious links** in issues, PRs, or comments (pastebin scrapers, redirect
chains, unfamiliar shortlinks, link-shortener URLs without context).
- **Behavior or language violating**
[GitHub's Acceptable Use Policies](https://docs.github.com/site-policy/acceptable-use-policies).
- **Behavior or language violating** the [Code of Conduct](CODE_OF_CONDUCT.md), or the terms of
the site where it is posted (GitLab's, on the mirror).
- **Off-topic / rambling reports** that don't get to the point (e.g. *"Good morning, today is a
beautiful day, I was just wondering if maybe…"*). Get straight to the problem.
- **PRs that touch hundreds of files for a one-line fix** (a typical sign of an auto-formatter run
@@ -63,7 +152,8 @@ ban — no exceptions:
## Conduct
By participating you agree to the [Code of Conduct](CODE_OF_CONDUCT.md). Be respectful; do not
use the project or its spaces to attack, insult, or harass others.
use the project or its spaces to attack, insult, or harass others. Report problems to
[code@poli0981.dev](mailto:code@poli0981.dev).
## License
+102
View File
@@ -0,0 +1,102 @@
# ACCESSIBILITY.md sends every accessibility barrier here. It is its own form rather than part of the
# bug report because a barrier needs different facts: what the reporter uses to read or operate the
# screen, and how far it stops them. Nothing here asks about the reporter themself.
name: Accessibility problem
description: Something in CommandForge can't be reached, read or seen — with the keyboard, a screen reader, a contrast theme, Magnifier, a larger text size or another aid
labels: ["accessibility"]
body:
- type: markdown
attributes:
value: |
Thank you for telling us. **You never need to tell us anything about yourself or a disability** — what you use
and what happened is enough. Screenshots and recordings help but are optional. Accessibility fixes are always
in scope.
If you couldn't read or answer a **Caution or Dangerous confirmation**, say so below: it is a safety problem
too, and it is handled first.
Rather not post in public? Write to **accessibility@poli0981.dev** instead. What CommandForge
aims for and what it can't do yet: [ACCESSIBILITY.md](../src/branch/main/ACCESSIBILITY.md).
- type: textarea
id: task
attributes:
label: What were you trying to do?
placeholder: "e.g. run a command from the catalog, read a command's output, change the theme"
validations:
required: true
- type: textarea
id: what-happened
attributes:
label: What happened instead?
description: What you heard, saw or could not do — and what you expected.
validations:
required: true
- type: textarea
id: steps
attributes:
label: How to get there
placeholder: |
1. Open the catalog (Ctrl+F)
2. Tab to …
3. …
- type: input
id: app-version
attributes:
label: CommandForge version
description: More (⋯) → About, or Settings → About
validations:
required: true
- type: input
id: os
attributes:
label: Windows version
placeholder: "Windows 11 24H2 (26100) — run winver"
validations:
required: true
- type: dropdown
id: aid
attributes:
label: What do you use?
multiple: true
options:
- Keyboard only
- Narrator
- NVDA
- JAWS
- Windows Magnifier
- A Windows contrast theme
- A larger text size or display scaling
- Voice Access or other speech input
- Something else (say below)
validations:
required: true
- type: input
id: aid-version
attributes:
label: Its version, if you know it
placeholder: "e.g. NVDA 2026.1"
- type: dropdown
id: severity
attributes:
label: How much does it stop you?
description: Optional — the maintainer sets it when reading the report (ACCESSIBILITY.md, "How serious it is").
options:
- Not sure
- Critical — I can't do the task at all
- Serious — only with great difficulty or a workaround
- Moderate — it is tiring or inconsistent
- Minor — it barely gets in the way
- type: textarea
id: more
attributes:
label: Anything else
description: A screenshot, a recording, or the log file from More (⋯) → Report a bug (you review it before attaching).
+11 -7
View File
@@ -6,9 +6,13 @@ body:
attributes:
value: |
Thanks for the report. **Get straight to the point** — vague or off-topic reports may be
closed (see [CONTRIBUTING.md](../blob/main/.github/CONTRIBUTING.md)).
**Do not report security vulnerabilities here** — use
[private reporting](../security/advisories/new) instead.
closed (see [CONTRIBUTING.md](../src/branch/main/.github/CONTRIBUTING.md)).
**Do not report security vulnerabilities here** — e-mail
**security@poli0981.dev** instead.
A catalog command that is outdated or uses the wrong syntax has its own form (**Command — add,
fix or remove**), and so does a barrier for the keyboard, a screen reader or larger text
(**Accessibility problem**). In the app, **More (⋯) → Report a bug** fills this form in.
- type: textarea
id: what-happened
attributes:
@@ -30,7 +34,7 @@ body:
id: app-version
attributes:
label: CommandForge version
description: Settings → About (e.g. 1.0.0)
description: More (⋯) → About CommandForge (e.g. 2.2.0)
validations:
required: true
- type: input
@@ -45,8 +49,8 @@ body:
attributes:
label: Logs (optional)
description: |
Optionally attach exported logs (Tools → Export logs). **Review them first** — they may
contain machine-specific paths/names. Do not paste secrets.
Optionally attach the log from **More (⋯) → Report a bug → Export log (.zip)**. **Review it
first** — it may contain machine-specific paths and names. Do not paste secrets.
- type: checkboxes
id: checks
attributes:
@@ -54,5 +58,5 @@ body:
options:
- label: I'm using the latest release.
required: true
- label: This is not a security vulnerability (those go through private reporting).
- label: This is not a security vulnerability (those go to security@poli0981.dev).
required: true
@@ -0,0 +1,83 @@
name: Command — add, fix or remove
description: Propose a catalog command, or report one that is outdated or uses the wrong syntax
labels: ["catalog"]
body:
- type: markdown
attributes:
value: |
Every command in CommandForge is a vetted entry of its read-only catalog. A request is checked
against Microsoft's documentation and tried before it ships — see
[Adding a command](../src/branch/main/.github/CONTRIBUTING.md#adding-a-command).
**A command that could cause harm** — it deletes what it shouldn't, weakens security, or does
something other than it says — is a security problem: e-mail it to
**security@poli0981.dev**, not here.
- type: dropdown
id: request
attributes:
label: What should change?
options:
- Add a command
- Fix a command (outdated, wrong syntax, wrong danger level)
- Remove a command
validations:
required: true
- type: input
id: command
attributes:
label: Command (to fix or remove)
description: Its title as the app shows it, or its ID from the command's details.
placeholder: e.g. Flush DNS cache (net.flushdns)
- type: textarea
id: command-line
attributes:
label: Command line
description: The exact command line it should run (for a new or fixed command).
render: shell
- type: textarea
id: purpose
attributes:
label: What it does and why
description: What the command does and who needs it; for a fix, what goes wrong today.
validations:
required: true
- type: dropdown
id: danger-level
attributes:
label: Danger level
description: |
Safe: read-only or undone the way it was made. Caution: changes system state, recoverable.
Dangerous: may lose data or leave Windows unstable.
options:
- Safe
- Caution
- Dangerous
- Not sure
- type: dropdown
id: admin
attributes:
label: Needs administrator rights?
options:
- "Yes"
- "No"
- Not sure
- type: input
id: windows-versions
attributes:
label: Windows versions
description: Where it works, or where it stopped working.
placeholder: e.g. Windows 11 24H2 and later
- type: textarea
id: sources
attributes:
label: Sources
description: Microsoft's documentation, or another reliable reference for the command and its syntax.
- type: checkboxes
id: checks
attributes:
label: Confirmations
options:
- label: The command is a tool that comes with Windows (nothing downloaded from elsewhere).
required: true
- label: It is not a command that could cause harm (those go to security@poli0981.dev).
required: true
+12 -6
View File
@@ -1,8 +1,14 @@
# Gitea reads these forms (.github/ISSUE_TEMPLATE), but only the maintainer can open issues there:
# the instance's registration is closed. Everyone else uses the public mirror on GitLab, which reads
# .gitlab/issue_templates instead.
blank_issues_enabled: false
contact_links:
- name: Security vulnerability (private)
url: https://github.com/poli0981/CommandForge/security/advisories/new
about: Report security vulnerabilities privately — do NOT open a public issue.
- name: Question / discussion
url: https://github.com/poli0981/CommandForge/discussions
about: Ask a question or discuss ideas before filing an issue.
- name: Report an issue or open a merge request (GitLab mirror)
url: https://gitlab.com/poli0981/CommandForge/-/issues/new
about: Issues and merge requests from everyone go to the public mirror on GitLab.
- name: Security vulnerability or harmful command (private, by e-mail)
url: https://git.poli0981.dev/poli0981/CommandForge/src/branch/main/.github/SECURITY.md
about: Write to security@poli0981.dev; do NOT open a public issue, here or on GitLab.
- name: Accessibility statement
url: https://git.poli0981.dev/poli0981/CommandForge/src/branch/main/ACCESSIBILITY.md
about: What works with the keyboard, screen readers and larger text, and the known limitations.
+22 -5
View File
@@ -1,13 +1,23 @@
name: Feature request
description: Suggest a feature or a new command for the catalog
description: A new feature, only when it fits the project and is genuinely necessary (maintenance mode)
labels: ["enhancement"]
body:
- type: markdown
attributes:
value: |
Thanks for the idea. Keep it concise and specific. For a **new command**, note that every
command must be a vetted, read-only catalog entry (no arbitrary execution) — see
[CONTRIBUTING.md](../blob/main/.github/CONTRIBUTING.md).
**CommandForge is in maintenance mode.** A new feature is added only when it clearly fits the
project and is genuinely necessary — for example, to keep the app safe or working on a new
Windows build. Other requests are closed with a link to
[the policy](../src/branch/main/.github/CONTRIBUTING.md#maintenance-mode-what-we-accept).
A catalog command to add, fix or remove has its own form: **Command — add, fix or remove**.
- type: checkboxes
id: scope
attributes:
label: Maintenance mode
options:
- label: I have read the maintenance-mode policy, and this is not a catalog command.
required: true
- type: textarea
id: problem
attributes:
@@ -15,11 +25,18 @@ body:
description: What are you trying to do, and why is it hard today?
validations:
required: true
- type: textarea
id: necessity
attributes:
label: Why is it necessary?
description: What breaks, or stays unsafe or out of reach, without it?
validations:
required: true
- type: textarea
id: proposal
attributes:
label: Proposed solution
description: What should CommandForge do? For a new command, give the exact command line and its danger level.
description: What should CommandForge do?
validations:
required: true
- type: textarea
+64
View File
@@ -0,0 +1,64 @@
name: Translation fix
description: Wording that doesn't suit the culture or the local tone, or spelling that could mislead
labels: ["translation"]
body:
- type: markdown
attributes:
value: |
CommandForge is shown in English, Vietnamese, Japanese, Simplified Chinese and Spanish. The
text other than English is AI-translated, so corrections from people who speak the language
are very welcome.
- type: dropdown
id: language
attributes:
label: Language
options:
- English
- Tiếng Việt
- 日本語
- 简体中文
- Español
validations:
required: true
- type: input
id: where
attributes:
label: Where in the app
placeholder: e.g. Settings › Appearance, or the confirmation of a Dangerous command
validations:
required: true
- type: textarea
id: current
attributes:
label: Text today
validations:
required: true
- type: textarea
id: suggestion
attributes:
label: Suggested text
validations:
required: true
- type: dropdown
id: reason
attributes:
label: What is wrong with it?
options:
- It doesn't suit the culture or the local tone
- The spelling or wording could mislead
- The meaning is wrong
- Something else
validations:
required: true
- type: textarea
id: more
attributes:
label: Anything else
description: Why the suggested text is better, or other places with the same wording.
- type: checkboxes
id: checks
attributes:
label: Confirmations
options:
- label: I'm using the latest release (the text may have changed already).
required: true
+11 -2
View File
@@ -11,11 +11,20 @@ Do NOT delete tests or use --no-verify to bypass hooks.
<!-- e.g. Closes #123 -->
## Scope
<!-- CommandForge is in maintenance mode: .github/CONTRIBUTING.md#maintenance-mode-what-we-accept -->
- [ ] This is within maintenance mode: a dependency or security update, a platform update, a catalog command added, fixed or removed, a bug, UI/UX or accessibility fix, or a translation fix — or a new feature agreed in an issue as genuinely necessary
## Checklist
- [ ] `dotnet build -c Release` passes with **0 warnings**
- [ ] `dotnet test` passes (and I added/updated tests for new behavior)
- [ ] `dotnet format` applied; no unrelated reformatting
- [ ] `dotnet format --verify-no-changes` passes; no unrelated reformatting
- [ ] No tests deleted/disabled; hooks not bypassed (`--no-verify` not used)
- [ ] If I added a command: it's a vetted catalog entry with correct `requiresAdmin`/`dangerLevel`, EN+VI strings, and no arbitrary-execution path
- [ ] My commits are signed (GPG or SSH)
- [ ] New or changed UI text is in all five `Strings*.resx` files (EN, VI, JA, zh-Hans, ES) — no hardcoded strings
- [ ] If I added a command: it's a vetted catalog entry with correct `requiresAdmin`/`dangerLevel`, strings in all five languages, and no arbitrary-execution path
- [ ] If I changed a screen: every control without text has an `AutomationProperties.Name` from the `.resx`, list items are named by what they show, icons are `ctl:DecorativeIcon`, and I tried it with the keyboard alone (and Narrator if I could) — see [ACCESSIBILITY.md](../ACCESSIBILITY.md#for-contributors)
- [ ] **AI disclosure:** I have disclosed any AI assistance used (delete if none)
+92 -25
View File
@@ -1,48 +1,115 @@
# Security Policy
CommandForge runs system-level commands, some elevated, so security is a top priority.
CommandForge runs system-level commands, some as administrator, so security is a top priority.
## Supported versions
| Version | Supported |
|---|---|
| 2.3.x (latest) | ✅ |
| < 2.3 | ❌ — please update (2.2.0 and older can't update themselves: install the latest release once by hand, see [UPDATES.md](../UPDATES.md)) |
Only the **latest release** receives security fixes. Please update before reporting.
CommandForge is in **maintenance mode** since 2.2.0, and security work goes on: a High or Critical
vulnerability in CommandForge, a dependency or the toolchain (the .NET runtime it ships with, for
example) gets an urgent patch release; a Moderate one goes into the next routine update. A catalog
command that could cause harm is reported here too, privately.
## Reporting a vulnerability
**Do not open a public issue for security vulnerabilities.**
**Report privately by e-mail: [security@poli0981.dev](mailto:security@poli0981.dev).**
Use **[GitHub private vulnerability reporting](https://github.com/poli0981/CommandForge/security/advisories/new)**
(Security → Advisories → Report a vulnerability). Include:
**Do not open a public issue for security vulnerabilities** — not on the GitLab mirror
(`gitlab.com/poli0981/CommandForge`), where issues are public, and not anywhere else. If one is
opened there by mistake, it is made confidential and the conversation continues by e-mail. (GitHub's
private vulnerability reporting is gone with the GitHub account.)
- affected version (Settings → About),
Please include:
- the affected version (More → About in the app),
- steps to reproduce,
- impact.
- the impact you observed or expect.
We aim to acknowledge reports within a reasonable time and will credit reporters who wish to be
named. Please give us a reasonable window to fix before any public disclosure.
named. Please give us a reasonable window to fix the issue before any public disclosure.
## Security model (summary)
## Security model
- **Vetted, read-only catalog.** Every runnable command is in an embedded, maintainer-reviewed
catalog. The app never loads arbitrary commands from files/users/network and self-elevates.
- **Least privilege.** The UI runs `asInvoker` (non-elevated). Only a separate `Elevator` helper
runs as Administrator, and only when needed (one UAC prompt per session). The Elevator accepts
only a `commandId` validated against its own embedded catalog — never an arbitrary command
string over the pipe.
- **Transparency.** The exact command line is shown before it runs.
- **No telemetry.** The only network call is the GitHub update check.
CommandForge guards the line between your normal (non-elevated) session and administrator rights:
no file, setting, network response or other program running as you should be able to decide what
runs elevated.
## Code signing & distribution integrity
- **Vetted, read-only catalog.** Every command that can run as administrator is in a catalog that
is built into the app and reviewed by the maintainer. The app never loads catalog commands from
files, users or the network. When the catalog loads, contradictory or unsafe records are rejected
(for example, unknown placeholders, or a Caution/Dangerous command without a confirmation).
- **Least privilege.** The UI runs as the invoking user (`asInvoker`). Admin commands go to a
separate helper, `CommandForge.Elevator`, which starts with one UAC prompt per session; you can
end the session at any time. The helper accepts only a **command ID**, which it looks up in its
own copy of the catalog — never a command line.
- **Authenticated channel.** The named pipe has a random name and an access list for your account
only, and each end verifies the other: the app accepts only the helper process it launched, and
the helper serves only `CommandForge.Wpf.exe` from its own folder. The helper connects with
Identification-level impersonation and writes no files; its diagnostics travel back to the app's
log through the pipe.
- **Trusted paths and environment.** Catalog programs resolve to absolute paths in `System32` or
the Windows folder, never through a search of the per-user app folder. Elevated commands get an
environment rebuilt from trusted sources (the system directory, known folders, HKLM), so per-user
variables such as `PSModulePath`, `COR_PROFILER`, `SystemRoot` or `windir` can't redirect what an
elevated command loads or deletes. The `{SystemDrive}`, `{SystemRoot}` and `{UserProfile}`
placeholders in the catalog are filled from the same trusted values, and PowerShell always runs
with `-NoProfile -NonInteractive`. The helper ignores `DOTNET_STARTUP_HOOKS`.
- **Your own commands stay unprivileged.** Commands you add under *My commands* are stored apart
from the catalog and always run without administrator rights.
- **Transparency and confirmation.** The exact command line is shown before it runs. Caution
commands ask first; Dangerous commands require typing the command's name or ID, and that check
can't be turned off. A System Restore Point can be created first.
- **Containment.** Commands whose output is captured run in a kill-on-close job object, so closing
or crashing the app doesn't leave them running.
- **No telemetry.** The only network connection the app makes is the update check against
`https://releases.poli0981.dev/commandforge` (see [PRIVACY.md](../PRIVACY.md)). The feed is
static files over HTTPS; no token or account is involved.
Releases are **not code-signed yet**, so SmartScreen may warn "unknown publisher" and some AV
engines may show false positives (common for admin tools). Mitigations:
### Known limitations
- We **do not obfuscate** (obfuscation is a leading cause of AV false positives).
- Every release publishes **SHA-256 checksums** (`checksums.txt`) and a **VirusTotal** link in the
release notes.
- The source is public (GPLv3) and CI runs **CodeQL** on every change.
- **Per-user installation.** Velopack installs the app under `%LocalAppData%\CommandForge`, a
folder your account can write to. Malware already running as you could replace the app's files —
including the elevated helper — and wait for you to approve the next UAC prompt. This applies to
every per-user app (UAC does not separate programs running as the same user), and since releases
aren't Authenticode-signed yet, the UAC prompt can't show a verified publisher either. Keep
untrusted software off your account, and approve the prompt only right after you started an
admin command and it names `CommandForge.Elevator`.
- **winget** is an App Execution Alias in `%LocalAppData%\Microsoft\WindowsApps`, another per-user
folder. The catalog's winget commands start it from there, including the ones that run as
administrator, so the same caveat applies.
- **Commands do what they say.** Commands you choose to run can change system settings, use the
network (winget, DNS tests…) or delete data by design; read the preview and see
[DISCLAIMER.md](../DISCLAIMER.md).
Code signing (Azure Trusted Signing, or SignPath Foundation for OSS) is planned for a future
release.
## Distribution integrity
Releases are **not Authenticode-signed yet**, so SmartScreen may warn about an unknown publisher
and some antivirus engines may show false positives (common for admin tools). Instead:
- Every release is built by the release workflow on Gitea Actions
(`git.poli0981.dev/poli0981/CommandForge`) from a signed tag on `main`; the workflow and its
logs are public. Build-provenance attestations ended with the move from GitHub (Gitea has no
OIDC signing).
- **SHA-256 checksums** (`<version>/SHA256SUMS`), a **CycloneDX SBOM** (`<version>/sbom.cdx.json`)
and, when a scan was made, **VirusTotal** links come with every release, under
`https://releases.poli0981.dev/commandforge/`.
- The code is **not obfuscated** (obfuscation is a leading cause of false positives), and the
source is public under the GPLv3.
- CI runs **Qodana** (JetBrains' inspections and security rules), **gitleaks** over the whole
history, **Opengrep** (SAST), **osv-scanner**, and a **NuGetAudit** restore that fails on known
vulnerabilities in direct and transitive packages; the workflows are linted with **actionlint**
and every action is pinned to a commit SHA. A self-hosted **Renovate** keeps dependencies and
those pins current, with separate pull requests for security fixes; `main` is protected and
takes changes through pull requests that pass the build.
Code signing (Azure Trusted Signing, or SignPath Foundation for open source) is planned for a
future release.
## Malicious contributions
+10
View File
@@ -0,0 +1,10 @@
# actionlint settings (security.yml, job `workflow-lint`, and a local `actionlint` run from the
# repository root), as in the ops repository poli0981/.github. Only Gitea features that actionlint
# does not know are ignored here; everything else stays an error.
paths:
.gitea/workflows/*.yml:
ignore:
# Gitea's own token scope for releases (ops runbook §3.2 item 5)
- 'unknown permission scope "releases"'
# Gitea resolves full-URL actions; a bare owner/repo goes to github.com (ops runbook §1)
- 'specifying action "https://gitea\.com/[^"]+" in invalid format'
-17
View File
@@ -1,17 +0,0 @@
version: 2
updates:
- package-ecosystem: nuget
directory: "/"
schedule:
interval: weekly
open-pull-requests-limit: 5
commit-message:
prefix: "deps"
- package-ecosystem: github-actions
directory: "/"
schedule:
interval: weekly
open-pull-requests-limit: 5
commit-message:
prefix: "ci"
-23
View File
@@ -1,23 +0,0 @@
name: Announce Release
# Posts a release announcement to Discord (reuses the shared workflow in poli0981/.github).
# Requires repo/org secret DISCORD_RELEASES_WEBHOOK (or DISCORD_REPO_WEBHOOK); optional
# DISCORD_PING_ROLE_ID. No-op effect if those secrets are unset (the job will error — set them
# or disable this workflow).
on:
release:
types: [published]
workflow_dispatch:
inputs:
tag:
description: Release tag to announce (e.g. v0.3.0)
required: true
type: string
jobs:
announce:
uses: poli0981/.github/.github/workflows/announce-release.yml@main
with:
tag_override: ${{ github.event.inputs.tag || '' }}
secrets: inherit
-34
View File
@@ -1,34 +0,0 @@
name: Build
on:
push:
branches: [main]
pull_request:
branches: [main]
workflow_dispatch:
permissions:
contents: read
jobs:
build:
# WPF (net10.0-windows) only builds on Windows.
runs-on: windows-latest
steps:
- uses: actions/checkout@v6
- uses: actions/setup-dotnet@v5
with:
dotnet-version: '10.0.x'
- name: Restore
run: dotnet restore CommandForge.slnx
- name: Verify formatting
run: dotnet format CommandForge.slnx --verify-no-changes --no-restore
- name: Build (Release, warnings = errors)
run: dotnet build CommandForge.slnx -c Release --no-restore
- name: Test
run: dotnet test CommandForge.slnx -c Release --no-build
-45
View File
@@ -1,45 +0,0 @@
name: CodeQL
# Project-specific CodeQL (not the shared reusable codeql-csharp.yml): this is a WPF
# (net10.0-windows) app that only builds on Windows and uses a .slnx solution, whereas the
# reusable workflow runs on ubuntu and looks for a .sln.
on:
push:
branches: [main]
pull_request:
branches: [main]
schedule:
- cron: '37 14 * * 1' # Mondays 14:37 UTC
workflow_dispatch:
permissions:
actions: read
contents: read
security-events: write
jobs:
analyze:
name: Analyze (csharp)
runs-on: windows-latest
timeout-minutes: 30
steps:
- uses: actions/checkout@v6
- uses: actions/setup-dotnet@v5
with:
dotnet-version: '10.0.x'
- name: Initialize CodeQL
uses: github/codeql-action/init@v4
with:
languages: csharp
queries: security-extended
- name: Build
run: dotnet build CommandForge.slnx -c Release
- name: Perform CodeQL Analysis
uses: github/codeql-action/analyze@v4
with:
category: "/language:csharp"
-14
View File
@@ -1,14 +0,0 @@
name: Notify CI Failure
# Posts a Discord alert when the Build workflow fails on main (reuses the shared workflow in
# poli0981/.github). Requires repo/org secret DISCORD_CI_WEBHOOK.
on:
workflow_run:
workflows: ["Build"]
types: [completed]
jobs:
notify:
uses: poli0981/.github/.github/workflows/notify-ci-failure.yml@main
secrets: inherit
-97
View File
@@ -1,97 +0,0 @@
name: Release
# Triggered by pushing a SemVer tag (vX.Y.Z). Builds a self-contained, Velopack-packaged
# release and publishes it to GitHub Releases with SHA-256 checksums and (optionally) a
# VirusTotal scan. No code signing yet (see SECURITY.md).
on:
push:
tags: ['v*']
workflow_dispatch:
inputs:
version:
description: 'Version without the leading v (e.g. 0.3.0)'
required: true
type: string
permissions:
contents: write
jobs:
release:
runs-on: windows-latest
env:
REPO_URL: https://github.com/poli0981/CommandForge
VT_API_KEY: ${{ secrets.VT_API_KEY }}
steps:
- uses: actions/checkout@v6
- uses: actions/setup-dotnet@v5
with:
dotnet-version: '10.0.x'
- name: Resolve version and tag
id: ver
shell: pwsh
run: |
if ('${{ github.event_name }}' -eq 'workflow_dispatch') {
$version = '${{ github.event.inputs.version }}'
$tag = "v$version"
} else {
$tag = '${{ github.ref_name }}'
$version = $tag -replace '^v', ''
}
"version=$version" >> $env:GITHUB_OUTPUT
"tag=$tag" >> $env:GITHUB_OUTPUT
Write-Host "Releasing $version (tag $tag)"
- name: Install Velopack CLI (vpk)
shell: pwsh
run: |
dotnet tool install -g vpk
"$env:USERPROFILE\.dotnet\tools" >> $env:GITHUB_PATH
- name: Download previous release (delta base)
continue-on-error: true # first release has nothing to download
run: vpk download github --repoUrl $env:REPO_URL --token ${{ secrets.GITHUB_TOKEN }}
shell: pwsh
- name: Publish + pack (Velopack)
run: ./scripts/pack.ps1 -Version ${{ steps.ver.outputs.version }}
shell: pwsh
- name: Publish GitHub Release (Velopack)
run: >
vpk upload github
--repoUrl $env:REPO_URL
--token ${{ secrets.GITHUB_TOKEN }}
--publish
--releaseName "CommandForge ${{ steps.ver.outputs.version }}"
--tag ${{ steps.ver.outputs.tag }}
shell: pwsh
- name: SHA-256 checksums
shell: pwsh
run: |
$rel = Join-Path (Get-Location) 'Releases'
$checksums = Join-Path $rel 'checksums.txt'
# NOTE: filter with Where-Object, not Get-ChildItem -Exclude — the latter returns nothing
# without a trailing wildcard/-Recurse, which produced an empty checksums.txt (HTTP 400).
Get-ChildItem -Path $rel -File |
Where-Object { $_.Name -ne 'checksums.txt' } |
Get-FileHash -Algorithm SHA256 |
ForEach-Object { '{0} {1}' -f $_.Hash.ToLower(), (Split-Path $_.Path -Leaf) } |
Out-File $checksums -Encoding ascii
gh release upload ${{ steps.ver.outputs.tag }} $checksums --clobber
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
- name: VirusTotal scan (optional)
if: env.VT_API_KEY != ''
uses: crazy-max/ghaction-virustotal@v5
with:
vt_api_key: ${{ env.VT_API_KEY }}
update_release_body: true
files: |
Releases/*-Setup.exe
Releases/*-full.nupkg
+4
View File
@@ -24,6 +24,8 @@ publish/
AppPackages/
*.nupkg
*.snupkg
# scripts/release-assets.ps1 (SBOM, SHA256SUMS, release notes)
r2-release/
# ── .NET / NuGet ────────────────────────────────────────────────
project.lock.json
@@ -65,6 +67,8 @@ artifacts/
*.trx
*.coverage
*.coveragexml
# SonarScanner for .NET working folder (local analysis runs)
.sonarqube/
# ── OS noise ────────────────────────────────────────────────────
Thumbs.db
+54
View File
@@ -0,0 +1,54 @@
<!--
Thank you for telling us. You never need to tell us anything about yourself or a disability: what you
use and what happened is enough. Screenshots and recordings help but are optional. Accessibility fixes
are always in scope.
If you couldn't read or answer a Caution or Dangerous confirmation, say so below: it is a safety
problem too, and it is handled first.
Rather not post in public? Write to accessibility@poli0981.dev instead. What CommandForge aims for and
what it can't do yet: https://git.poli0981.dev/poli0981/CommandForge/src/branch/main/ACCESSIBILITY.md
-->
## What were you trying to do?
<!-- e.g. run a command from the catalog, read a command's output, change the theme -->
## What happened instead?
<!-- What you heard, saw or could not do, and what you expected. -->
## How to get there
1. Open the catalog (Ctrl+F)
2. Tab to …
3. …
## CommandForge version
<!-- More (⋯) → About, or Settings → About -->
## Windows version
<!-- e.g. Windows 11 24H2 (26100): run winver -->
## What do you use?
<!-- Keyboard only / Narrator / NVDA / JAWS / Windows Magnifier / a Windows contrast theme /
a larger text size or display scaling / Voice Access or other speech input / something else -->
## Its version, if you know it
<!-- e.g. NVDA 2026.1 -->
## How much does it stop you?
<!-- Optional: Not sure / Critical (I can't do the task at all) / Serious (only with great difficulty or
a workaround) / Moderate (it is tiring or inconsistent) / Minor (it barely gets in the way) -->
## Anything else
<!-- A screenshot, a recording, or the log file from More (⋯) → Report a bug (you review it before
attaching). -->
/label ~accessibility
+39
View File
@@ -0,0 +1,39 @@
<!--
Thanks for the report. Get straight to the point: vague or off-topic reports may be closed (see
CONTRIBUTING.md: https://git.poli0981.dev/poli0981/CommandForge/src/branch/main/.github/CONTRIBUTING.md).
Do NOT report security vulnerabilities here: e-mail security@poli0981.dev instead.
A catalog command that is outdated or uses the wrong syntax has its own template (Command), and so
does a barrier for the keyboard, a screen reader or larger text (Accessibility). In the app,
More (⋯) → Report a bug fills this template in.
-->
## What happened?
<!-- What you expected vs. what actually happened. -->
## Steps to reproduce
1. Open …
2. Run command …
3. See …
## CommandForge version
<!-- More (⋯) → About CommandForge, e.g. 2.3.0 -->
## Windows version / build
<!-- e.g. Windows 11 23H2 (22631): run `winver` -->
## Logs (optional)
<!-- Optionally attach the log from More (⋯) → Report a bug → Export log (.zip). Review it first: it
may contain machine-specific paths and names. Do not paste secrets. -->
## Confirmations
- [ ] I'm using the latest release.
- [ ] This is not a security vulnerability (those go to security@poli0981.dev).
/label ~bug
+52
View File
@@ -0,0 +1,52 @@
<!--
Every command in CommandForge is a vetted entry of its read-only catalog. A request is checked
against Microsoft's documentation and tried before it ships: see "Adding a command" in
https://git.poli0981.dev/poli0981/CommandForge/src/branch/main/.github/CONTRIBUTING.md#adding-a-command
A command that could cause harm (it deletes what it shouldn't, weakens security, or does something
other than it says) is a security problem: e-mail security@poli0981.dev, do NOT report it here.
-->
## What should change?
<!-- One of: Add a command / Fix a command (outdated, wrong syntax, wrong danger level) / Remove a command -->
## Command (to fix or remove)
<!-- Its title as the app shows it, or its ID from the command's details, e.g. Flush DNS cache (net.flushdns) -->
## Command line
<!-- The exact command line it should run (for a new or fixed command). -->
```shell
```
## What it does and why
<!-- What the command does and who needs it; for a fix, what goes wrong today. -->
## Danger level
<!-- Safe: read-only or undone the way it was made. Caution: changes system state, recoverable.
Dangerous: may lose data or leave Windows unstable. Or: Not sure. -->
## Needs administrator rights?
<!-- Yes / No / Not sure -->
## Windows versions
<!-- Where it works, or where it stopped working, e.g. Windows 11 24H2 and later -->
## Sources
<!-- Microsoft's documentation, or another reliable reference for the command and its syntax. -->
## Confirmations
- [ ] The command is a tool that comes with Windows (nothing downloaded from elsewhere).
- [ ] It is not a command that could cause harm (those go to security@poli0981.dev).
/label ~catalog
@@ -0,0 +1,28 @@
<!--
CommandForge is in maintenance mode. A new feature is added only when it clearly fits the project
and is genuinely necessary, for example to keep the app safe or working on a new Windows build.
Other requests are closed with a link to the policy:
https://git.poli0981.dev/poli0981/CommandForge/src/branch/main/.github/CONTRIBUTING.md#maintenance-mode-what-we-accept
A catalog command to add, fix or remove has its own template: Command.
-->
## Maintenance mode
- [ ] I have read the maintenance-mode policy, and this is not a catalog command.
## Problem / motivation
<!-- What are you trying to do, and why is it hard today? -->
## Why is it necessary?
<!-- What breaks, or stays unsafe or out of reach, without it? -->
## Proposed solution
<!-- What should CommandForge do? -->
## Alternatives considered
/label ~enhancement
+31
View File
@@ -0,0 +1,31 @@
<!--
CommandForge is shown in English, Vietnamese, Japanese, Simplified Chinese and Spanish. The text other
than English is AI-translated, so corrections from people who speak the language are very welcome.
-->
## Language
<!-- English / Tiếng Việt / 日本語 / 简体中文 / Español -->
## Where in the app
<!-- e.g. Settings › Appearance, or the confirmation of a Dangerous command -->
## Text today
## Suggested text
## What is wrong with it?
<!-- It doesn't suit the culture or the local tone / The spelling or wording could mislead /
The meaning is wrong / Something else -->
## Anything else
<!-- Why the suggested text is better, or other places with the same wording. -->
## Confirmations
- [ ] I'm using the latest release (the text may have changed already).
/label ~translation
@@ -0,0 +1,33 @@
<!--
Keep merge requests focused and small. Read CONTRIBUTING.md before submitting:
https://git.poli0981.dev/poli0981/CommandForge/src/branch/main/.github/CONTRIBUTING.md
This is the GitLab mirror. GitLab CI does not run here: the maintainer applies the change on Gitea
(the canonical repository), where CI runs, and the mirror then shows this merge request as merged.
Do NOT delete tests or use --no-verify to bypass hooks.
-->
## Summary
<!-- What does this merge request change, and why? -->
## Related issue
<!-- e.g. Closes #123 -->
## Scope
<!-- CommandForge is in maintenance mode: .github/CONTRIBUTING.md#maintenance-mode-what-we-accept -->
- [ ] This is within maintenance mode: a dependency or security update, a platform update, a catalog command added, fixed or removed, a bug, UI/UX or accessibility fix, or a translation fix, or a new feature agreed in an issue as genuinely necessary
## Checklist
- [ ] `dotnet build -c Release` passes with **0 warnings**
- [ ] `dotnet test` passes (and I added/updated tests for new behavior)
- [ ] `dotnet format --verify-no-changes` passes; no unrelated reformatting
- [ ] No tests deleted/disabled; hooks not bypassed (`--no-verify` not used)
- [ ] New or changed UI text is in all five `Strings*.resx` files (EN, VI, JA, zh-Hans, ES), no hardcoded strings
- [ ] If I added a command: it's a vetted catalog entry with correct `requiresAdmin`/`dangerLevel`, strings in all five languages, and no arbitrary-execution path
- [ ] If I changed a screen: every control without text has an `AutomationProperties.Name` from the `.resx`, list items are named by what they show, icons are `ctl:DecorativeIcon`, and I tried it with the keyboard alone (and Narrator if I could): see ACCESSIBILITY.md, "For contributors"
- [ ] **AI disclosure:** I have disclosed any AI assistance used (delete if none)
+190
View File
@@ -0,0 +1,190 @@
# Accessibility
CommandForge should be usable by everyone who maintains a Windows PC — with a keyboard alone, with
a screen reader, with a Windows contrast theme or Magnifier, with larger text, and without telling
colours apart. This page says what CommandForge aims for, what works today, how that is checked,
what does not work yet and what to do instead, and how to tell us about a barrier. It is written
for the person who has just met one.
CommandForge is a desktop program: its own window, its dialogs and the notifications it shows.
The commands it runs are Windows' own tools (winget, DISM, PowerShell and others), so the text
they print is theirs.
*Last reviewed on 2026-11-16 for version 2.2.0 by the maintainer, poli0981. In the app: More (⋯) ▸
About CommandForge ▸ Accessibility.*
## What CommandForge aims for
- **WCAG 2.2 at level AA**, applied to desktop software as W3C's
[WCAG2ICT](https://www.w3.org/TR/wcag2ict-22/) guidance explains. This is a goal that guides the
work, not a claim: no formal evaluation has been made, and CommandForge does not say it conforms
to any standard.
- **Every task can be done with the keyboard alone.**
- **A screen reader can read every control and every value**, in the language CommandForge is shown
in, and hears what changes: a command starting, needing permission, finishing.
- **Text and controls keep their contrast** in the light and the dark theme and under Windows
contrast themes, and **colour is never the only way something is shown.**
- **Text follows your size settings**: the app's own font size and Windows' Text size.
Accessibility fixes are always in scope, whatever else the project is or isn't taking on.
## What works today
### The keyboard
| Keys | What they do |
|---|---|
| **Tab** and **Shift+Tab** | Move through a page or a dialog in reading order. In a list, Tab moves into the buttons of the selected row (its star, Undo, Run again). |
| The **arrow keys** | Move inside a list: commands, History, the console's output, the Log viewer, the Command Palette's results. On a splitter, they resize the panes. |
| **F6** and **Shift+F6** | Jump between the navigation pane, the page and the console. |
| **Enter** or **Space** | Press the button, switch or box that has the focus. **Enter** on a command in the catalog moves to its **Run** button; on a run in History it opens that command; in the Command Palette it opens the highlighted one. |
| **Esc** | Closes a dialog the way its **Cancel** or **Close** button does: nothing is changed. |
| **Ctrl+K**, **Ctrl+F**, **Ctrl+H**, **Ctrl+,**, **Ctrl+L** | Open the Command Palette, search the current list, Home, Settings, the Log viewer — and move the keyboard into that page. |
Every shortcut is in the user guide, under [Keyboard shortcuts](USAGE.md#keyboard-shortcuts), and in
the app under More (⋯) ▸ Keyboard shortcuts.
- **A risky command can't be run by accident.** A Caution command asks first, with **Cancel**
focused and as the default; a Dangerous one waits until its name or ID is typed — the ID is read
out with the box.
- **Ctrl+Q does nothing while you are typing** in a text box (other than a search box), so a slip
can't close the app in the middle of an edit.
### Screen readers
- **Every button, switch, box and list item has a name**, from the same translations as the screen.
A button repeated on every row names its row — *Undo: Flush DNS cache*, *Move up: Clean temporary
files*, *Add to favorites: Check disk*.
- **A command is read with its risk**: *Reset Windows Update, Caution, Requires admin, May require
restart* — what a sighted user reads from the coloured dot and the badges.
- **Every page has a heading**: its title is a heading of the first level, each section one of the
second, so a screen reader's heading keys move from section to section.
- **What appears is said as it appears**: a command starting, waiting for administrator permission,
finishing (with its result, exit code and time, and whether Windows must restart), how many
commands a search found, the highlighted result in the Command Palette (*Flush DNS cache, Safe, 2
of 14*), every notification at the bottom of the window, and an update's progress.
- **The console and the Log viewer can be read line by line**, and an error line starts with
*Error*.
- **Icons are left out**: they only decorate the word beside them, so a screen reader never stops on
a symbol. A notice on a page is read in full with its kind first — *Warning: These commands are
not part of the vetted catalog…*
- **Dialogs say they are dialogs**, keep the focus inside them until they close, and give it back.
### Seeing the screen
- **Light, dark, or the same as Windows** (Settings ▸ Appearance ▸ Theme). Every colour comes from
the theme.
- **Windows contrast themes** (Settings ▸ Accessibility ▸ Contrast themes) always win over the app's
own theme, as soon as you turn one on or off. Dimmed text and badge icons are drawn at full
strength under a contrast theme.
- **Text size**: the app's own font size (Small, Medium, Large) is multiplied by Windows' **Text
size** (Settings ▸ Accessibility ▸ Text size, up to 225 %), picked up when you come back to the
app; at the largest sizes the navigation pane widens to fit its labels. **Display scaling** works
at any size, on every screen, and so does **Magnifier** (Windows logo key + Plus).
- **Colour is never the only signal**: risk levels always come with their word or an icon, and an
error line in the console has a bar at its left as well as its colour.
- **Animations follow Windows' Animation effects setting**: with it off, pages switch at once.
### Languages
CommandForge is shown in English, Vietnamese, Japanese, Simplified Chinese or Spanish (Settings ▸
Appearance ▸ Language), and the names a screen reader reads come from the same translations. The
documents — the user guide, this page, the legal texts — are in English.
## How it is checked
- **On every build**, by the project's tests: every control that shows no text has a name; the
items of a list are named by what they show, not by a program type; every page title is a
heading; the app declares that it follows each screen's scaling; no colour is written into a
screen; every icon is kept out of a screen reader's way; this page's links work and it never
claims conformance. The key every name uses must exist in all five languages. Other tests run the
fixes on real controls of the WPF-UI library the app is built with, so a library update that
renames one of their parts is caught before a release.
- **By an automated scan**: Axe.Windows, Microsoft's UI Automation rules (the engine of Accessibility
Insights for Windows), over every page of the running app, the first-start terms and the console
after a command, in the light and the dark theme and at Windows' largest Text size. Version 2.2.0
passes it with no error.
- **By hand**: the maintainer used CommandForge 2.1.0 with the keyboard alone (mouse disconnected)
and with Narrator on Windows 11 in November 2026 and found no major problem. Version 2.2.0 then
fixed everything a review of every screen found — the result of a command was not announced, the
console could not be read line by line, the Command Palette's highlight was silent, and some lists
read a program type instead of their text, among others. The 2.2.0 build was checked the same way
before its release, and with a Windows contrast theme, a larger Text size and Animation effects
off.
- **Not tested yet**: NVDA, JAWS, Voice Access, touch, and Windows 10. They should work through the
same Windows interface Narrator uses, but nobody has checked.
## Known limitations
Each one with what to do instead. A barrier that is not on this list is worth reporting.
- **A command's output is the text Windows' tool prints**, in Windows' language, sometimes with
progress bars drawn out of characters. Read it line by line, or use **Copy all** or **Save** above
the console to read it elsewhere.
- **There are no access keys** (Alt with an underlined letter): with five languages they would clash.
Use the shortcuts above, Tab and F6.
- **The title bar's Minimize, Maximize and Close buttons are not Tab stops** (screen readers still
find them by name). Use **Alt+F4** or **Ctrl+Q** to close, and Windows' own **Windows logo key +
arrow** keys to maximize, restore or minimize.
- **Expanding a card in Settings still animates** when Windows' Animation effects is off: the
animation belongs to the WPF-UI library the app is built with.
- **At the largest sizes** (Large font with Windows' Text size near 225 %), some pages and dialogs
need scrolling, and the title bar's search box shows the start of its text (its tooltip and its
name have all of it; Ctrl+K opens it).
- **Icons keep their size**: Windows' Text size enlarges text only. Display scaling (Settings ▸
System ▸ Display ▸ Scale) or Magnifier enlarges everything.
- **The windows Windows itself shows** — the administrator (UAC) prompt, choosing a file — are
Windows', not CommandForge's.
## Report an accessibility problem
1. Open an issue on the GitLab mirror with the
[Accessibility template](https://gitlab.com/poli0981/CommandForge/-/issues/new?issuable_template=Accessibility),
or write to **[accessibility@poli0981.dev](mailto:accessibility@poli0981.dev)** if you'd rather not
use GitLab or not post in public.
2. Say what you were trying to do and what happened instead; your CommandForge version (More ▸ About)
and your Windows version; and what you use — the keyboard alone, Narrator, NVDA, JAWS, Magnifier,
a contrast theme, a larger text size — with its version. The steps to get there help, and so does
a screenshot or a recording, but neither is required. **You never need to tell us anything about
yourself or a disability.**
3. If you want to attach details from your PC, **More ▸ Report a bug** gathers them and exports the
log as a file you review first; nothing is uploaded by itself.
**A safety prompt you could not perceive or answer** — a Caution or Dangerous confirmation — is a
safety problem as well: say so in the report, and it is handled first.
### How serious it is
You do not have to choose; the maintainer sets it when reading the report.
| Severity | What it means | For example |
|---|---|---|
| **Critical** | A task cannot be done at all. | A Dangerous command's confirmation cannot be answered with the keyboard; the terms cannot be accepted on first start; a command's result is never conveyed. |
| **Serious** | It can be done only with great difficulty or a workaround. | A command's output can be read only after saving it to a file. |
| **Moderate** | It is tiring or inconsistent. | A name that differs from what the screen shows; an extra stop for Tab. |
| **Minor** | It barely gets in the way. | A tooltip the keyboard cannot reach, when its words are shown elsewhere too. |
### What happens next
CommandForge has one maintainer, so there are no promised times. Every report is read and answered,
without doubting what you describe. Critical problems come before other work; a workaround, when
there is one, is written on the issue; the fix ships in a release, and the issue is closed once you
say it works for you — or when a fix has been out for a while and nobody has answered.
## Who looks after this
The maintainer, poli0981, keeps this page and the checks behind it, and reviews both for each release
that changes a screen. A change to CommandForge that moves anything on this page changes the page in
the same pull request.
## For contributors
A change to the app keeps what the tests above hold: a name, from the translations in all five
languages, for every control that shows no text and every list item; colours only from the theme.
Say in the pull request what you checked with the keyboard and with Narrator (Accessibility Insights
for Windows is a good companion). The rules are in [CONTRIBUTING.md](.github/CONTRIBUTING.md).
## Feedback
To improve this page, open an issue or a pull request. A barrier goes through the form above, so that
it is not lost.
+81 -18
View File
@@ -3,12 +3,20 @@
## Requirements
- Windows 10 (22H2) or Windows 11
- **.NET 10 SDK** (`dotnet --version` → `10.0.x`)
- For packaging: the **Velopack CLI** — `dotnet tool install -g vpk`
- **.NET 10 SDK** — the feature band is pinned in `global.json` (`dotnet --version` → `10.0.4xx`)
- Admin rights are only needed to **test** elevated commands, not to build.
The solution file is **`CommandForge.slnx`** (the XML solution format).
| Project | Role |
|---|---|
| `src/CommandForge.Domain` | Entities; no dependencies |
| `src/CommandForge.Application` | Use cases and ports; depends only on Domain |
| `src/CommandForge.Infrastructure` | Processes, registry, catalog, storage, Velopack, logging |
| `src/CommandForge.Wpf` | The WPF app (WPF-UI); namespace `CommandForge.Desktop` |
| `helper/CommandForge.Elevator` | The elevated helper that runs admin commands over a named pipe |
| `tests/CommandForge.Tests` | xUnit v3 tests |
## Build, run, test
```bash
@@ -18,42 +26,97 @@ dotnet run --project src/CommandForge.Wpf
dotnet test CommandForge.slnx
```
## Code style
The tests use xUnit v3 in VSTest mode (`xunit.v3.mtp-off`), so `dotnet test` and the coverlet
collector work as usual.
## Code style and analysis
```bash
dotnet format CommandForge.slnx # apply formatting
dotnet format CommandForge.slnx --verify-no-changes # CI gate
```
The build enforces analyzers as errors (`TreatWarningsAsErrors`, `EnforceCodeStyleInBuild`),
including unused-using/unused-member rules.
The build treats warnings as errors and enforces the .NET analyzers, code style
(`EnforceCodeStyleInBuild`) and **SonarAnalyzer.CSharp** (Sonar's C# rules as a Roslyn analyzer),
including unused-using and unused-member rules.
To measure test coverage (Coverlet, OpenCover format):
```bash
dotnet test CommandForge.slnx --collect "XPlat Code Coverage;Format=opencover"
```
## Dependencies
- Package versions live in **each `.csproj`**; SonarAnalyzer is referenced once from
`Directory.Build.props`. Central Package Management is not used (a convention from the GitHub
days, when the dependency graph didn't read `Directory.Packages.props`; Renovate reads both).
- Every restore runs a **NuGet audit** of direct and transitive packages; moderate or higher
advisories fail the build.
- A self-hosted **Renovate** on Gitea (the shared preset `poli0981/renovate-config`, plus
`renovate.json`) proposes updates: minor and patch ones grouped, each held for 3 days after
release, security fixes at once. Velopack and the `vpk` tool move together; majors wait for
approval on the Dependency Dashboard, and new majors of the .NET SDK and of
`Microsoft.Extensions.*` are never proposed: moving to a new .NET major is a deliberate
migration, done by hand.
## Publish (self-contained) + package
The Velopack CLI is pinned as a local tool in `.config/dotnet-tools.json`, at the same version as
the Velopack library:
```bash
# One-step helper (publish + vpk pack):
pwsh ./scripts/pack.ps1 -Version 0.3.0
dotnet tool restore
pwsh ./scripts/pack.ps1 -Version 2.0.0 # publish + vpk pack
pwsh ./scripts/pack.ps1 -Version 2.0.0 -SkipPack # publish only
```
`pack.ps1` runs a self-contained `win-x64` publish (stamping the assembly version so the in-app
version matches the release) and then `vpk pack`. It writes these artifacts to `Releases/`:
`pack.ps1` (parameters: `-Version`, `-Runtime` = `win-x64`, `-Configuration` = `Release`,
`-SkipPack`):
- runs a self-contained **ReadyToRun** publish, stamping the version so the in-app version matches
the release;
- checks that `CommandForge.Elevator` is in the publish folder (the
`PublishElevatorOnPublish` target in `src/CommandForge.Wpf/CommandForge.Wpf.csproj` publishes it
alongside the app);
- runs `vpk pack` with `--runtime`, so the installer and updater helpers are native x64, and stops
on any non-zero exit code.
It writes these artifacts to `Releases/`:
- `CommandForge-win-Setup.exe` — the installer
- `CommandForge-<version>-full.nupkg` — full package
- `CommandForge-<version>-delta.nupkg` — delta package (only when a previous full is present)
- `CommandForge-<version>-delta.nupkg` — delta package (only when a previous full package is
present; see [UPDATES.md](UPDATES.md))
- `releases.win.json` / `RELEASES` — the update manifest read by the app
The `CommandForge.Elevator` helper is published into the same folder automatically (see the
`PublishElevatorOnPublish` target in `src/CommandForge.Wpf/CommandForge.Wpf.csproj`).
`scripts/release-assets.ps1 -Version <X.Y.Z>`, run after `pack.ps1`, adds what a release publishes
next to them: the CycloneDX SBOM, `SHA256SUMS` and the release notes, under `r2-release/` (the
release workflow runs both; locally they are a dry run).
> No code signing yet — see [SECURITY.md](.github/SECURITY.md). Don't add a signing step until
> Azure Trusted Signing (or SignPath Foundation for OSS) is set up.
> No Authenticode signing yet — see [SECURITY.md](.github/SECURITY.md). Don't add a signing step
> until Azure Trusted Signing (or SignPath Foundation for OSS) is set up.
## CI
- **`build.yml`** — restore + `dotnet format --verify-no-changes` + Release build + tests on every
PR/push to `main` (Windows).
- **`codeql.yml`** — CodeQL C# analysis (Windows, builds `CommandForge.slnx`).
- **`release.yml`** — see [RELEASING.md](RELEASING.md).
CI runs on **Gitea Actions** at `git.poli0981.dev/poli0981/CommandForge`, on the maintainer's
own runner: `windows-latest` jobs run in host mode on a Windows 11 PC, `ubuntu-latest` jobs in
Docker. The runner is online when the PC is on, so a run can wait; scheduled jobs only fall in
13:00–16:00 UTC. The shared workflows come from the ops repository `poli0981/.github`, pinned by
commit SHA (its migration runbook is `docs/GITEA-MIGRATION.md` there). All workflows pin actions
to full commit SHAs and use least-privilege permissions.
| Workflow | What it does |
|---|---|
| `build.yml` | `build`: restore, `dotnet format --verify-no-changes`, Release build, tests (results and coverage kept as an artifact). `package`: publish and `vpk pack` exactly like a release. |
| `security.yml` | `workflow-lint`: actionlint + shellcheck on the workflows. `scan` (ops `security.yml`): gitleaks over the full history, Opengrep (SAST, report only), osv-scanner, and a NuGetAudit restore that fails on high/critical advisories. Also weekly, Friday 14:11 UTC. |
| `qodana.yml` | JetBrains Qodana for .NET (Rider's inspections, native mode on Windows) over the whole solution, after a Release build, through the ops `reusable-qodana.yml` (Qodana CLI); settings in `qodana.yaml`, and the gate is zero problems. Results go to Qodana Cloud and the `qodana-report` artifact. Advisory. Needs the `QODANA_TOKEN` secret. |
| `release.yml` | Tag-triggered release to Cloudflare R2 and a Gitea release — see [RELEASING.md](RELEASING.md). A manual run on a branch is a dry run. |
| `announce-release.yml` | Posts a release to Discord (also called by `release.yml`). |
| `notify-ci-failure.yml` | Posts a Discord alert when Build, Qodana or Security fails on `main` (`DISCORD_CI_WEBHOOK`). |
| `notify-release-pipeline.yml` | Posts every Release run's result to Discord (`DISCORD_RELEASE_PIPELINE_WEBHOOK`). |
`main` is protected on Gitea: no force push or deletion, and changes land through pull requests
whose `Build` checks pass.
See [UPDATES.md](UPDATES.md) for how auto-update works.
+432
View File
@@ -0,0 +1,432 @@
# Changelog
All notable changes to **CommandForge** are documented here.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
## [Unreleased]
## [2.3.0] — 2026-11-26
CommandForge has moved off GitHub, where the account behind the project was suspended: the source
now lives at [git.poli0981.dev](https://git.poli0981.dev/poli0981/CommandForge), issues go to the
[GitLab mirror](https://gitlab.com/poli0981/CommandForge/-/issues), and releases and updates come
from `releases.poli0981.dev`. **If you have 2.2.0 or older, install this version once by hand**
([installer](https://releases.poli0981.dev/commandforge/CommandForge-win-Setup.exe)): those
versions look for updates on GitHub and will never find one. Run it over your installation; your
settings, favorites, history, recipes and commands stay.
### Fixed
- **Updates** work again: the app checks `https://releases.poli0981.dev/commandforge` (Cloudflare
R2) for new versions, the only address it contacts on its own. When a check fails, the message
names "the update server" instead of GitHub; offline, not found (404), refused or rate-limited
(403/429) and server errors (5xx) are still told apart.
- **Links** that opened GitHub open the project on Gitea: **Source code** (it was "GitHub") in
About and Settings, the user guide, the accessibility statement, and the full texts of the EULA,
GPLv3, Disclaimer and Privacy policy ("Read the full text online").
### Changed
- **Report a bug** opens a new issue on the GitLab mirror with the title and the Bug template
already answered: what happened (and a crash's error code), the app version and the Windows
version. Nothing is sent until you submit it.
- **Privacy policy:** the update check goes to `releases.poli0981.dev`, served by Cloudflare,
instead of GitHub. Nothing else changed (no telemetry, no data collected), so you aren't asked to
accept the terms again.
- **Security reports** go to security@poli0981.dev only; accessibility barriers to the GitLab
*Accessibility* template or accessibility@poli0981.dev.
- **Release files:** every release publishes `SHA256SUMS` and a CycloneDX SBOM next to its files
(`releases.poli0981.dev/commandforge/<version>/`). The checksums cover what the version ships:
the installer, the portable zip and its packages. (The `checksums.txt` of 2.1.0 and 2.2.0 had
wrong lines for the two feed files, which are rewritten on every release.)
- **CI** runs on Gitea Actions: Build, Security (gitleaks, Opengrep, osv-scanner, NuGetAudit,
actionlint) and Qodana through its CLI replace CodeQL, SonarCloud, OpenSSF Scorecard and
dependency review; a self-hosted Renovate replaces Dependabot.
- Dependencies: SonarAnalyzer 10.37; the CycloneDX tool 6.3.2 (release SBOM) is added and the
SonarScanner removed. The app keeps the .NET 10.0.15 runtime (SDK 10.0.404), still the latest.
### Removed
- Build-provenance attestations (`gh attestation verify`), GitHub Discussions and GitHub's private
vulnerability reporting: none of them exists outside GitHub. Releases are still built from signed
tags by a public workflow, with checksums, an SBOM and an optional VirusTotal scan.
## [2.2.0] — 2026-11-16
CommandForge is now **stable and in maintenance mode** (see
[Project status](https://github.com/poli0981/CommandForge#project-status)). This release brings an
accessibility review of every screen, the November 2026 .NET security update and Qodana code
analysis.
### Added
- **Accessibility statement**: [ACCESSIBILITY.md](https://github.com/poli0981/CommandForge/blob/main/ACCESSIBILITY.md)
says what works with the keyboard, screen readers, contrast themes and larger text, what doesn't
yet, and how to report a barrier: an *Accessibility problem* issue form or
accessibility@poli0981.dev. In the app: More (⋯) → About CommandForge → Accessibility.
- **F6 / Shift+F6** move between the navigation pane, the page and the console.
- **Windows' Text size** (Settings › Accessibility › Text size) now enlarges the app's text too, on
top of its own Small / Medium / Large.
### Changed
- **Maintenance mode**: the work now goes into security, dependency and platform updates, catalog
commands, and bug, UI/UX, accessibility and translation fixes; a new feature only when it is
genuinely necessary. The policy is in
[CONTRIBUTING.md](https://github.com/poli0981/CommandForge/blob/main/.github/CONTRIBUTING.md#maintenance-mode-what-we-accept),
and the issue forms follow it, with two new ones: *Command — add, fix or remove* and
*Translation fix*.
- Code quality: JetBrains Qodana for .NET now inspects `main` and every pull request from CI, next
to SonarCloud: Rider's C#, XAML and resource inspections and JetBrains' security rules, run
natively on Windows. The gate is zero problems. Its first report also fixed a process object that
could be left undisposed when a command's program could not be found, and the command history
being read outside the lock it is written under.
- Dependencies: Microsoft.Extensions.DependencyInjection 10.0.15, CsWin32 0.3.371, SonarAnalyzer
10.36, SonarScanner for .NET 12.1.0, xUnit v3 4.0.3, Microsoft.NET.Test.Sdk 18.12.0, coverlet
10.1.1; in CI, setup-dotnet 6.1.0 and CodeQL action 4.39.3.
- Dependabot no longer proposes new major versions of .NET or Microsoft.Extensions: moving to a
new .NET major is a deliberate migration, done by hand.
### Fixed
- **Screen readers** (Narrator, NVDA, JAWS) now hear what appears: a command starting, waiting for
administrator permission and finishing — with its result, exit code, time and whether Windows must
restart —, how many commands a search found, the Command Palette's highlighted result and its
position, every notification, and an update's progress.
- **The console and the Log viewer** can be read line by line with the arrow keys; an error line is
read as an error and has a bar at its left, not only a colour.
- **Lists, options and buttons** are read by their text instead of a program type name (the language
lists, the Recipes command list, My commands, the Log viewer, the shortcuts list), commands with
their risk level and badges, and a button repeated on every row names its row ("Undo: …").
- **Keyboard**: after Ctrl+H, Ctrl+, or Ctrl+L, or choosing a page in the pane, the keyboard moves
into that page; a command opened from Home, History or the palette gets the focus in the catalog;
Enter opens the selected command in the catalog and in History; Tab reaches a row's star, Undo and
Run again; the catalog's splitters move with the arrow keys; every window and dialog starts with
the keyboard inside it, and a Caution confirmation on Cancel.
- **Unnamed controls** got names: the navigation pane's toggle and its two lists, the title bar's
buttons (Maximize is read as Restore down while the window is maximized), a search box's clear
button, the Settings cards and expanders, the Debug panel's tabs and
the four "Read on GitHub" links; the Dangerous confirmation also reads the command's ID, and
Settings' theme and font size choices are read as groups. The log level list is translated.
- **Icons are no longer read** as stray symbols: they only decorate the word beside them, so a
screen reader skips them. A notice on a page is read in full with its kind ("Warning: These
commands are not part of the vetted catalog…"); before, a screen reader could not reach its text.
A blank line in the console is read as "Blank line", and the frame around each page is no longer
an empty stop for Tab.
- **Seeing the screen**: dimmed text and badge icons are drawn at full strength under a Windows
contrast theme, low-contrast grey text is darker, cut-off text shows in full as a tooltip, page
transitions follow Windows' Animation effects setting, and lists and cards no longer clip larger
text. At the largest text sizes the navigation pane widens to fit its labels, the catalog's
filters and a command's badges wrap instead of running off the edge, and the title bar's search
box ends in "…" with its full text as a tooltip.
- **Ctrl+Q** no longer closes the app while you are typing in a text box (a search box excepted).
- **Report a bug** opens GitHub's *Bug report* form with the description, the crash code and the
versions filled in. Before, GitHub showed anyone who isn't a collaborator the list of forms
instead, and what the app had filled in was lost.
### Security
- Built with the .NET 10.0.404 SDK, so the app ships the .NET 10.0.15 runtime (the November 2026
security update).
- Links and folders are opened only when they are `https:` or `mailto:` addresses or existing
folders: Windows runs whatever the shell is handed, so a `file:` address or an unknown protocol is
refused.
## [2.1.0] — 2026-10-26
Three new categories and 37 new commands (the catalog grows from 261 to 298), the October 2026
.NET security update, and test coverage in SonarCloud.
### Added
- **Devices & Peripherals** (11 commands): Bluetooth, printer and display settings, the classic
Sound panel; lists of USB devices, cameras, audio devices, paired Bluetooth devices, printers and
disconnected devices Windows still remembers; and **Scan for hardware changes**.
- **Backup & Recovery** (9 commands): Recovery settings, the Windows Recovery Environment status
and **Enable Windows Recovery Environment**, System Protection, restore point disk usage, File
History, Backup settings, Backup and Restore (Windows 7) and the Recovery Drive wizard.
- **Accounts & Sign-in** (8 commands): Sign-in options, your account info, other users, User
Accounts (netplwiz), Credential Manager, saved Windows credentials (`cmdkey /list`, no
passwords), the password and lockout policy, and local groups.
- **9 commands in existing categories:** available sleep states, what woke the PC last and the
devices allowed to wake it (Power); motherboard and language & region (System Info); disabled
services (Services & Startup); PATH entries with missing folders flagged (Developer); proxy and
VPN settings (Network).
### Changed
- Settings → Advanced and Portable info now say whether this copy updates itself ("Installed or
portable" / "Development build") instead of "Installed" / "Portable / dev": the portable zip
from the releases page updates itself like the installed app.
- Releases: the notes come from this changelog and list the VirusTotal reports; the provenance
attestations now also cover the portable zip, and `checksums.txt` lists exactly the files you
can download.
- Code quality: SonarCloud now analyzes `main` and every pull request from CI, with test coverage
(SonarScanner for .NET 12, OpenCover reports), instead of Automatic Analysis. New code must be
at least 80% covered to pass the quality gate.
- Dependencies: Microsoft.Extensions.DependencyInjection 10.0.14, CsWin32 0.3.367, CodeQL action
4.39.1.
### Security
- Built with the .NET 10.0.403 SDK, so the app ships the .NET 10.0.14 runtime (the October 2026
security update).
## [2.0.0] — 2026-10-21
A redesign in the Fluent style of Windows 11, plus a broad safety, reliability and security
overhaul. Settings, favorites, history, recipes and your own commands carry over unchanged.
### Added
- **Fluent UI (WPF-UI 4.3).** A Mica window with its own title bar, a navigation pane (Home,
Favorites, History, Recipes, My commands and the catalog with its 12 categories and counts; Log
viewer, Debug panel and Settings at the bottom), in-window dialogs, snackbar notifications and
the Windows accent color. Light, dark or system theme; High Contrast always wins.
- **Resizable window** (minimum 960×600, default 1200×780) that remembers its size, position and
maximized state, and never reopens off-screen.
- **Title bar:** a search box for the whole catalog (`Ctrl+K`), an admin-session indicator with
**End admin session**, and a **More** menu (Command Palette, Check for updates, Create System
Restore Point, export logs, open the config and log folders, keyboard shortcuts, user guide,
report a bug, terms, About).
- **Catalog:** filter chips for Safe / Caution / Dangerous and Admin only, the estimated duration,
the command line with paths filled in, and a splitter between the details and the console.
- **Console:** one shared console for the catalog, recipes and your own commands — virtualized,
capped at 10,000 lines (with an "N earlier lines" note), **Copy all output**, **Save output to a
file**, a "Waiting for administrator permission…" status, and **Restart now** (asks first,
never while a command runs).
- A finished run shows a notification and flashes the taskbar button when the console isn't
visible; the taskbar button shows progress while a command runs.
- The Legal Gate lets you choose the app language before reading the terms.
- **20 new commands** (catalog grew from 241 to 261): restore point list, System Restore, Automatic
Maintenance, clock resync, DNS cache, listening ports, Wi-Fi interface details, third-party
scheduled tasks, Run keys, stopped automatic services, Windows Search restart, Store and optional
updates, UAC status, Core isolation, environment variables, WSL status, TRIM status, crash dumps
and battery charge.
- A **user guide** ([USAGE.md](USAGE.md)), linked from the More menu and About. About also lists
contact addresses for security reports and code questions.
- **Release integrity:** build-provenance attestations (`gh attestation verify`), an SPDX SBOM and
SHA-256 checksums are attached to every release.
### Changed
- **One set of safety rules.** Dangerous commands always ask with typing; Caution commands ask
unless you turn that off; a restore point is offered only for risky admin commands (or commands
flagged for one), so per-user tweaks no longer trigger a UAC prompt for it.
- **Type-to-confirm** accepts the command name regardless of case and Unicode form, or the command
ID, so Vietnamese input methods and Japanese/Chinese IMEs can confirm. Cancel is the default.
- **Recipes** no longer run Dangerous steps after a single Yes/No: an overview prompt is followed
by each risky step's own confirmation, with one restore point before the chain.
- **Search** returns relevant matches only (descriptions and tags must contain your words), ranks
titles better, highlights the right letters and ignores accents ("don dep" finds "Dọn dẹp").
- **Catalog safety and accuracy:**
- Automatic Disk Cleanup uses its own allow-list of safe handlers, so Downloads, the Recycle
Bin and Windows.old are never touched and your own `/sageset:1` choices are kept.
- Removing Windows.old and clearing the event logs are now Dangerous.
- Drive repair uses `Repair-Volume -OfflineScanAndFix`; drive letters and profile paths come
from your actual system drive and profile.
- PowerShell commands run with `-NoProfile -NonInteractive` and stop at the first error instead
of always printing success; cleanups report what they removed and what was in use.
- winget never prompts; activation status no longer needs VBScript; the Windows 11 Widgets
button opens Settings, because Windows now blocks that change from scripts.
- Switching the language changes only the app's text; number and date formats keep following
your regional settings.
- **Logs:** 14 daily files of at most 10 MB each (they grew without limit before). Every run is
logged as a one-line summary (ID, exit code, duration), never with its output.
- Faster startup: ReadyToRun publish and no Generic Host (about 20 fewer packages).
- Font size now scales every text and control live.
### Removed
- MaterialDesignThemes, Microsoft.Extensions.Hosting and Serilog.Extensions.Hosting.
### Fixed
- **Garbled output** from `sfc`, `wsl` and other native tools on non-English Windows: output is
decoded as UTF-16, UTF-8 or the OEM code page, whichever it is.
- The console could stay "running" forever when a run failed or was cancelled while the admin
helper was starting.
- A failed startup left an invisible process holding the single-instance lock, so every later
launch silently did nothing. The app now shows an error and exits.
- Settings, history, recipes, profiles and your commands are saved atomically. A damaged file is
kept as a backup instead of silently resetting everything (including the accepted terms).
- **Updates:** closing the update dialog with X cancels the download; the app no longer restarts
mid-command to apply an update; timeouts and other errors are reported instead of leaving the
dialog on "Checking".
- **Restore points:** "Windows already made one in the last 24 hours" is reported as skipped, not
as created; any other failure asks before running the command anyway.
- **Keyboard:** AltGr no longer triggers shortcuts (typing "@" on a German keyboard closed the
app); `Ctrl+B` toggles the navigation pane as advertised.
- History's Run again and Undo are disabled while a command runs; runs that never started are not
recorded.
- My commands: a quoted `cmd` is recognized and `/c` is no longer added twice.
- Exporting logs or settings to a locked path, or opening a link with no browser set up, shows a
message instead of the crash dialog. Imported settings files are validated.
- Crash support codes stay the same across runs.
- The Log Viewer refreshes once per burst of log events instead of once per event.
### Security
- Catalog programs resolve to absolute paths in System32/Windows, so a program planted in the
app's per-user folder can't run elevated; Launch commands pin their working directory.
- Elevated commands get an environment rebuilt from trusted sources: per-user variables such as
`PSModulePath`, `COR_PROFILER`, `SystemRoot` and `windir` can no longer redirect what an elevated
command loads or deletes. The elevated helper ignores `DOTNET_STARTUP_HOOKS`.
- The app and the elevated helper verify each other's process on the named pipe; the helper
connects with Identification-level impersonation and no longer writes files.
- Captured commands run in a kill-on-close job object.
- The catalog loader registers a command only after it passes validation; contradictory or unsafe
records are rejected.
- **CI and supply chain:** actions pinned to commit SHAs with least-privilege permissions, CodeQL
for C# and GitHub Actions, dependency review, OpenSSF Scorecard, a NuGet audit of transitive
packages, SonarAnalyzer rules enforced at build time, and a protected `main` branch with
required checks.
## [1.5.1] — 2026-07-09
### Fixed
- **Single instance:** launching the app while it is already running no longer opens a second
window. Later launches bring the existing window to the foreground (restoring it if minimized)
and then exit.
## [1.5.0] — 2026-07-08
### Added
- **40 new commands** (catalog grew from 201 to 241), focused on rarely-used and Windows-version-specific
features, gated by OS build so Windows 10-only commands are hidden on Windows 11 and vice-versa:
- **Windows 11-only tweaks & pages:** hide the Widgets and Copilot taskbar buttons; enable taskbar
"End task"; "Never combine + labels" taskbar; "More pins" Start layout; and open Dynamic Lighting,
Presence sensing and (24H2) Energy Saver settings.
- **Windows 10-only tweaks:** turn off News and Interests; hide the Meet Now, People and Cortana
buttons; and turn off all Start menu live tiles.
- **Diagnostics & system info:** current-user rights & groups, Start menu app IDs, Boot Configuration
(BCD), devices reporting problems, all event-log channels and Entra/AD device-join state.
- **Security, storage, power, network & developer:** local Administrators members, trusted root
certificates, all firewall rules and Recall feature status (24H2); SMART reliability counters,
volume dirty bit and sector-size info; active wake timers and reduced-size hibernation; Wi-Fi radio
capabilities, global TCP settings and a Wi-Fi history report; and Dev Drive status, Sudo for Windows
status, the Hyper-V VM list and the boot hypervisor launch type.
### Fixed
- **TPM Status** and **Defender Exclusions** now run with administrator elevation, so they return
results instead of appearing blank (both underlying queries require an elevated session).
## [1.4.0] — 2026-06-29
### Added
- **60 new commands and a new "Services & Startup" category** (catalog grew from 141 to 201):
- **Services & Startup** (new 12th category): restart the Print Spooler, Windows Audio, Windows
Update and BITS services; list running and automatic services; and open the Startup apps settings
and the Startup folder.
- **System info & storage:** battery health, network-adapter speed, disk health and SMART status,
page-file usage, local user accounts, time zone and Windows install date; plus a drive-usage
summary, largest temp files, partition list, fragmentation analysis, Disk Cleanup configuration
and a DiskPart disk/volume listing.
- **Network & diagnostics:** a public DNS lookup test, active TCP connections, firewall profiles,
shared folders, the hosts file and Network Connections; plus recent boot/shutdown and
unexpected-shutdown events, recent system errors, Print Management and Certificate Manager.
- **Cleanup, power & maintenance:** clear the icon cache, recent items and event logs; the Power
Saver plan and hibernate-now; and an online disk scan and a read-only system-file verification.
- **Security, updates & tweaks:** Defender threat history and exclusions, BitLocker volume details,
reset firewall to defaults, remove dynamic signatures and open Windows Security; update history,
Windows Update settings, App Installer self-update, package export, third-party drivers and
troubleshooters; and hide/show the Windows 11 taskbar search plus transparency, Snap-assist and
Telnet-client toggles.
## [1.3.0] — 2026-06-26
### Added
- **25 new commands and a new "Storage" category** (catalog grew from 116 to 141): optimize /
defragment C:, Disk Management, list volumes & free space, and open Storage settings; TPM status,
Secure Boot state and a computer & OS summary; network adapters, DNS servers and an internet
connectivity test; startup programs, Driver Verifier, Performance Monitor and a system health
report; clear crash dumps, Windows Error Reporting data and the DNS + ARP caches; lid-close and
monitor-timeout power toggles; and NumLock-at-startup and verbose sign-in toggles.
- **Two new UI languages — Simplified Chinese (简体中文) and Spanish (Español)** — joining English,
Vietnamese and Japanese. Selectable in Settings and the View menu and switching live without a
restart.
### Changed
- **Fixed main window size.** The main window is now a fixed 1100×720 and can no longer be resized
or maximized; the F11 full-screen shortcut has been removed.
## [1.2.0] — 2026-06-21
### Added
- **38 new commands** across all ten categories (catalog grew from 78 to 116): installed
updates / drivers / BIOS / programs / displays; active connections, ARP cache, routing table,
Wi-Fi profiles and WinHTTP proxy; dark/light mode and Windows 11 taskbar-alignment and
clock-seconds tweaks; thumbnail / font / Prefetch cleanup; the Balanced power plan, power
requests and a Fast Startup toggle; Task Manager, Device Manager, Services and Group Policy
result; winget source list and Microsoft Store reset; Defender status and full scan; firewall
on/off; WSL shutdown, Windows Sandbox off and a long-paths toggle.
- **Japanese (日本語) language.** A full Japanese translation joins English and Vietnamese,
selectable in Settings and the View menu and switching live without a restart.
### Changed
- **Version-aware command list.** Commands that only apply to a specific Windows version (such as
the Windows 11 taskbar and clock tweaks) are now hidden automatically when they do not apply to
your build of Windows.
## [1.1.1] — 2026-06-19
### Fixed
- **User commands hanging on `cmd`.** A user-defined command using `cmd` (e.g.
`ping google.com`) could stay "running" forever without responding. The process runner now
redirects and immediately closes the child's standard input, so an interactive `cmd` receives
EOF and exits instead of blocking. User commands that use `cmd` also get `/c` prepended
automatically (`cmd` + `ping google.com` runs as `cmd /c ping google.com`), and the run
confirmation shows the exact command line. PowerShell and other executables are unchanged.
- **Recipes — duplicate steps.** A command already in a recipe can no longer be added again, so a
recipe never runs the same command multiple times.
- **Sidebar.** Hid the vertical scrollbar on the command-groups list (still scrollable by wheel).
## [1.1.0] — 2026-06-19
### Added
- **Package & assembly metadata.** Product, author, company, copyright and repository information
are embedded in the assemblies (shown in About and file properties) and in the Velopack
installer.
- **Execution history.** A new History screen lists finished runs (newest first) with time, status
and duration, plus **Run again** and **Clear history**. Stored locally; no telemetry.
- **Import / export & profiles.** Export your appearance, behavior and favorites to a `.json` file
and import them on another machine. Save the current configuration as a named **profile**
(e.g. "Gaming PC", "Office") and switch between them.
- **Recipes (command chains).** Build a named sequence of vetted catalog commands and run them with
a single aggregated confirmation, **one UAC prompt** for an all-admin chain, and **stop-on-error**
(and stop-on-reboot-required) for safety.
- **User-defined commands ("My commands").** Add your own commands. They are kept entirely separate
from the vetted catalog and **always run without administrator rights**.
- **Registry before/after & undo.** For applicable tweaks, the affected registry values are read
before and after the run and a diff is shown in the console (read-only). History entries for
reversible commands offer **Undo**, which runs the command's vetted revert command — no arbitrary
registry writes.
- **Home maintenance suggestions** (e.g. low disk space → Disk Cleanup; long uptime → restart) and
**local natural-language search** (everyday phrases such as "clean disk" suggest a catalog
keyword). Both are 100% local — no cloud, no LLM.
## [1.0.0] — 2026-06-18
Initial public release.
### Added
- **Command catalog.** An embedded, vetted, read-only catalog of Windows commands organized by
category, with fuzzy search and a Command Palette (Ctrl+K) and an exact command-line preview.
- **Execution engine.** Real-time console output streamed off the UI thread, cancellation, and
restart-required detection (exit code `3010`).
- **Admin / UAC.** Elevated commands run through a separate `CommandForge.Elevator` broker over a
named pipe (one UAC prompt per session); the main UI stays non-elevated.
- **Safety.** Confirmation dialogs for Caution/Dangerous commands (type-to-confirm for Dangerous,
which cannot be disabled), optional System Restore Point, and revert for reversible tweaks.
- **Self-update** via Velopack (per-user, delta updates) from GitHub Releases.
- **Localization & theming.** Full English/Vietnamese UI, light/dark/system themes, and font
scaling.
- **Home dashboard** with recent commands, favorites and a read-only system-status widget.
- **Diagnostics.** Settings screen, Log Viewer (filter/export), Debug panel, a global crash handler
and a "Report a bug" flow.
- **Accessibility** (automation names, keyboard navigation, AA contrast) and a first-run Legal Gate
(EULA / GPLv3 / Disclaimer / Privacy).
- **CI/CD.** Build, test and CodeQL on every change; tag-triggered releases publish SHA-256
checksums (and an optional VirusTotal scan). No telemetry — the only network use is checking
GitHub for updates.
[Unreleased]: https://git.poli0981.dev/poli0981/CommandForge/compare/v2.3.0...main
[2.3.0]: https://git.poli0981.dev/poli0981/CommandForge/compare/v2.2.0...v2.3.0
[2.2.0]: https://git.poli0981.dev/poli0981/CommandForge/compare/v2.1.0...v2.2.0
[2.1.0]: https://git.poli0981.dev/poli0981/CommandForge/compare/v2.0.0...v2.1.0
[2.0.0]: https://git.poli0981.dev/poli0981/CommandForge/compare/v1.5.1...v2.0.0
[1.5.1]: https://git.poli0981.dev/poli0981/CommandForge/compare/v1.5.0...v1.5.1
[1.5.0]: https://git.poli0981.dev/poli0981/CommandForge/compare/v1.4.0...v1.5.0
[1.4.0]: https://git.poli0981.dev/poli0981/CommandForge/compare/v1.3.0...v1.4.0
[1.3.0]: https://git.poli0981.dev/poli0981/CommandForge/compare/v1.2.0...v1.3.0
[1.2.0]: https://git.poli0981.dev/poli0981/CommandForge/compare/v1.1.1...v1.2.0
[1.1.1]: https://git.poli0981.dev/poli0981/CommandForge/compare/v1.1.0...v1.1.1
[1.1.0]: https://git.poli0981.dev/poli0981/CommandForge/compare/v1.0.0...v1.1.0
[1.0.0]: https://git.poli0981.dev/poli0981/CommandForge/src/tag/v1.0.0
+51 -18
View File
@@ -10,7 +10,14 @@
- **Chỉ Windows 10 (22H2) và 11**, x64 (ARM64 nếu được).
- **Open-source, GPLv3.**
- Cài & cập nhật bằng **Velopack** (unpackaged, không qua Store).
- Cài & cập nhật bằng **Velopack** (unpackaged, không qua Store); feed + gói trên Cloudflare R2 `https://releases.poli0981.dev/commandforge`.
- Mã nguồn chuẩn trên **Gitea** `git.poli0981.dev/poli0981/CommandForge` (tài khoản GitHub đã bị khóa từ 11/2026); issue/MR qua mirror GitLab `gitlab.com/poli0981/CommandForge` (xem [mục 9](#9-forge--ci)).
- **Trạng thái: ổn định, chế độ bảo trì** từ v2.2.0 (2026-11-16). Chỉ nhận: cập nhật dependency;
vá bảo mật (High/Critical → bản vá khẩn, Moderate → đợt cập nhật định kỳ kế tiếp); nâng cấp nền
tảng lớn (.NET mới); thêm/bớt/sửa lệnh catalog (lỗi thời, sai cú pháp, có thể gây hại — loại gây
hại báo riêng qua email `security@`); sửa lỗi, UI/UX, accessibility; sửa bản dịch. Tính năng mới
chỉ khi thật sự phù hợp và cần thiết. Nguồn chuẩn của chính sách:
`.github/CONTRIBUTING.md#maintenance-mode-what-we-accept`.
---
@@ -21,19 +28,20 @@
3. **Khởi động lại:** Phát hiện cần reboot bằng **exit code `3010`** (`ERROR_SUCCESS_REBOOT_REQUIRED`), không chỉ parse text.
4. **Ranh giới kiến trúc:** `Domain` không phụ thuộc gì. `Application` chỉ phụ thuộc `Domain`. `Infrastructure`/`Wpf` hiện thực các interface của `Application`. **Không bao giờ** để `Domain`/`Application` tham chiếu WPF hay Win32.
5. **Không obfuscate.** Mã GPLv3 vốn công khai; obfuscate vừa vô nghĩa vừa gây false-positive antivirus.
6. **Hiện chưa ký số** (sẽ thêm Azure Trusted Signing sau — xem `docs/Build.md`). Đừng thêm bước ký vào build/CI lúc này.
7. **Không telemetry.** Mạng duy nhất được phép: gọi GitHub để kiểm tra cập nhật. Bất kỳ thu thập dữ liệu nào khác đều bị cấm (vi phạm `docs/Privacy.md`).
6. **Hiện chưa ký số Authenticode** (sẽ thêm Azure Trusted Signing/SignPath sau — xem `docs/Build.md`). Đừng thêm bước ký Authenticode vào build/CI lúc này. SBOM (CycloneDX) và `SHA256SUMS` do `scripts/release-assets.ps1` tạo trong `release.yml` (tải lên `releases.poli0981.dev/commandforge/<version>/`) là bắt buộc và phải giữ. Attestation build-provenance đã bỏ khi rời GitHub (Gitea không có OIDC — quyết định D7 của runbook).
7. **Không telemetry.** Mạng duy nhất được phép: kiểm tra/tải cập nhật từ `https://releases.poli0981.dev/commandforge` (`ProductLinks.UpdateFeed`). Bất kỳ thu thập dữ liệu nào khác đều bị cấm (vi phạm `docs/Privacy.md`).
8. **Xác nhận trước lệnh nguy hiểm.** Lệnh `Caution`/`Dangerous` phải có hộp thoại xác nhận; không cho phép tắt xác nhận với nhóm `Dangerous`.
---
## 3. Tech stack (tóm tắt — chi tiết ở `docs/tech.md`)
- **.NET 10 (LTS), C# 14** · **WPF** + **Material Design In XAML**
- **CommunityToolkit.Mvvm** (MVVM) · **Microsoft.Extensions.DependencyInjection/Hosting** (DI)
- **.NET 10 (LTS), C# 14** · **WPF** + **WPF-UI 4.3** (Fluent, lepoco) — đã thay Material Design từ v2.0.0
- **CommunityToolkit.Mvvm** (MVVM) · **Microsoft.Extensions.DependencyInjection** (`ServiceCollection` + `ValidateOnBuild`; **không** dùng Generic Host)
- **CsWin32** (P/Invoke) · **Serilog** (logging) · `System.Threading.Channels`
- **Velopack** (`vpk`) cho cài đặt + cập nhật qua GitHub Releases
- i18n: `.resx` (EN/VI)
- **Velopack** (`vpk` pin làm local tool trong `.config/dotnet-tools.json`) cho cài đặt + cập nhật qua Cloudflare R2 (HTTP source); **CycloneDX** (local tool) tạo SBOM khi phát hành
- Test: **xUnit v3** (`xunit.v3.mtp-off`, chạy qua VSTest) · **SonarAnalyzer.CSharp** (Roslyn analyzer) chạy trong build · **Qodana** trong CI (không còn SonarCloud — D1)
- i18n: `.resx` 5 ngôn ngữ (EN/VI/JA/zh-Hans/ES)
---
@@ -43,8 +51,8 @@
src/
CommandForge.Domain/ # entities thuần
CommandForge.Application/ # use-cases + interfaces (ports)
CommandForge.Infrastructure/ # Process, registry, Velopack, GitHub, Serilog
CommandForge.Wpf/ # View + ViewModel + DI bootstrap + .resx
CommandForge.Infrastructure/ # Process, registry, Velopack, Serilog
CommandForge.Wpf/ # View + ViewModel + DI bootstrap + .resx (namespace: CommandForge.Desktop)
helper/
CommandForge.Elevator/ # tiến trình phụ chạy lệnh Admin (named pipe)
tests/
@@ -60,16 +68,27 @@ dotnet restore
dotnet build -c Debug
dotnet run --project src/CommandForge.Wpf
dotnet test
# Phát hành + đóng gói:
dotnet publish src/CommandForge.Wpf -c Release -r win-x64 --self-contained
vpk pack --packId CommandForge --packVersion <ver> --packDir <publishDir>
dotnet format CommandForge.slnx --verify-no-changes
# Phát hành + đóng gói (publish ReadyToRun + vpk pack → Releases/):
dotnet tool restore
pwsh ./scripts/pack.ps1 -Version <ver>
```
Phát hành thật: tag ký GPG `vX.Y.Z` trên `main` (khớp `<Version>`) → `.gitea/workflows/release.yml` → R2 + release Gitea + Discord (xem `RELEASING.md`). Chạy tay Release trên nhánh = dry run (không upload).
---
## 6. Quy ước code (chi tiết ở `docs/codestyle.md`)
- Code, định danh, comment kỹ thuật: **tiếng Anh**. Chuỗi hiển thị cho người dùng: **`.resx` (EN/VI)** — không hardcode chuỗi UI.
- Code, định danh, comment kỹ thuật: **tiếng Anh**. Chuỗi hiển thị cho người dùng: **`.resx` (EN/VI/JA/zh-Hans/ES)** — không hardcode chuỗi UI; mỗi key phải có ở cả 5 file (test `ResxKeyTests` quét UI để kiểm tra).
- Namespace tầng giao diện là `CommandForge.Desktop` (project/assembly/exe vẫn tên `CommandForge.Wpf`): namespace `CommandForge.Wpf` che namespace gốc `Wpf` của WPF-UI trong code XAML sinh ra.
- **Accessibility** (xem `ACCESSIBILITY.md`): control không có chữ phải có `AutomationProperties.Name`
từ `.resx`; item của danh sách được đặt tên qua `ItemContainerStyle`; icon dùng `ctl:DecorativeIcon`
(không dùng `ui:SymbolIcon`/`new SymbolIcon` — glyph vùng Unicode riêng bị Narrator đọc); không
truyền thông tin chỉ bằng màu; thông báo cho Narrator qua `INotificationService.Announce`.
`AccessibilityTests` và `WpfAccessibilityRuntimeTests` (STA, template WPF-UI thật) kiểm tra.
- WPF-UI: mỗi trang (UserControl trong NavigationView) phải đặt `Foreground="{DynamicResource TextFillColorPrimaryBrush}"` ở gốc (Frame không truyền màu chữ xuống); lớp con của `ContentDialog` phải gọi `SetResourceReference(StyleProperty, typeof(ContentDialog))` — `XamlConventionsTests` kiểm tra cả hai. Cỡ chữ dùng `DynamicResource AppFontSize*`.
- Version package đặt trong **từng `.csproj`** (không dùng Central Package Management — quy ước có từ thời GitHub; Renovate đọc được cả hai).
- Nullable reference types **bật**; `TreatWarningsAsErrors` **bật**; analyzers **bật**.
- `async/await` xuyên suốt cho I/O; không `async void` (trừ event handler); luôn truyền `CancellationToken`.
- MVVM bằng source-generator của CommunityToolkit (`[ObservableProperty]`, `[RelayCommand]`).
@@ -80,7 +99,7 @@ vpk pack --packId CommandForge --packVersion <ver> --packDir <publishDir>
## 7. Bất biến quan trọng khi đụng tới các vùng nhạy cảm
- **Thêm lệnh mới:** chỉ thêm vào catalog JSON (`Infrastructure/Catalog/commands.json`) theo schema ở `docs/CatalogCommand.md`; thêm key chuỗi vào `.resx`; viết test validate catalog. **Catalog sẽ được bổ sung/cập nhật liên tục theo thời gian** — giữ schema ổn định, dễ mở rộng.
- **Thêm lệnh mới:** chỉ thêm vào catalog JSON (`Infrastructure/Catalog/commands.json`) theo schema ở `docs/CatalogCommand.md`; thêm key chuỗi vào cả 5 file `.resx`; icon phải có trong `Converters/IconMap.cs`; PowerShell luôn `-NoProfile -NonInteractive`; dùng token `{SystemDrive}`/`{SystemRoot}`/`{UserProfile}` thay vì đường dẫn cứng; viết test validate catalog. **Catalog sẽ được bổ sung/cập nhật liên tục theo thời gian** — giữ schema ổn định, dễ mở rộng.
- **Sửa luồng nâng quyền:** đọc kỹ `docs/Security.md` trước.
- **Sửa luồng cập nhật:** xử lý đủ `404 / 403 / 429 / 5xx / offline` (KHÔNG có mã `419`).
@@ -93,7 +112,7 @@ vpk pack --packId CommandForge --packVersion <ver> --packDir <publishDir>
| `docs/tech.md` | Tech stack, third-party (font, update…), phiên bản |
| `docs/architectures.md` | Kiến trúc chi tiết, ports/adapters, elevation broker, threading |
| `docs/codestyle.md` | Chuẩn code C#/XAML, `.editorconfig`, analyzers |
| `docs/UI.md` | Đặc tả giao diện từng thành phần |
| `docs/UI.md` | Đặc tả giao diện từng thành phần (Fluent / WPF-UI) |
| `docs/CatalogCommand.md` | Toàn bộ lệnh + nhóm lệnh + schema |
| `docs/roadmap.md` | Lộ trình theo phase, milestone, version |
| `docs/note.md` | Ghi chú, quyết định, "gotcha", nhắc nhở |
@@ -101,7 +120,21 @@ vpk pack --packId CommandForge --packVersion <ver> --packDir <publishDir>
| `docs/Security.md` | Mô hình bảo mật, threat model, disclosure |
| `docs/Build.md` | Build, test, publish, release, CI |
| `docs/Testing.md` | Chiến lược kiểm thử |
| `docs/Changelog.md` | Nhật ký thay đổi |
| `LICENSE.md` / `Privacy.md` / `EULA.md` / `Disclaimer.md` | Pháp lý |
| `docs/Changelog.md` | Chỉ trỏ về `CHANGELOG.md` (gốc repo) |
| `docs/LICENSE.md` / `Privacy.md` / `EULA.md` / `Disclaimer.md` | Bản pháp lý nội bộ (bản công khai ở gốc repo là chuẩn) |
> ⚠️ Bộ tài liệu này nằm trong `.gitignore` (tài liệu nội bộ). Nếu sau này cần publish các file pháp lý (để Legal Gate trỏ link tới GitHub), tạo bản công khai riêng — xem `docs/note.md`.
> ⚠️ Thư mục `docs/` nằm trong `.gitignore` (tài liệu nội bộ, chỉ có trên máy).
**Tài liệu công khai (ở gốc repo, được commit):** `README.md`, `ACCESSIBILITY.md` (tuyên bố trợ năng — mục tiêu WCAG 2.2 AA, không phải tuyên bố tuân thủ; link "Accessibility" trong About), `USAGE.md` (hướng dẫn người dùng — link "User guide" trong app), `CHANGELOG.md`, `BUILD.md`, `RELEASING.md`, `UPDATES.md`, `PRIVACY.md`, `EULA.md`, `DISCLAIMER.md`, `THIRD-PARTY-NOTICES.md`, `MAINTAINERS.md`, `LICENSE`, và trong `.github/`: `SECURITY.md`, `CONTRIBUTING.md`, `CODE_OF_CONDUCT.md`. Legal Gate trỏ tới EULA/PRIVACY/DISCLAIMER/LICENSE công khai (trên Gitea, qua `ProductLinks`). Template issue/MR cho GitLab ở `.gitlab/`; `.github/ISSUE_TEMPLATE` giữ cho Gitea.
**Email liên hệ (@poli0981.dev):** `security@` (lỗ hổng — kênh riêng tư duy nhất, không bao giờ qua issue công khai) · `accessibility@` (rào cản trợ năng, cùng template *Accessibility* trên GitLab) · `privacy@` · `legal@` · `copyright@` / `dmca@` / `takedown@` (bản quyền, DMCA, yêu cầu gỡ bỏ khác) · `code@` (mã nguồn, đóng góp, báo cáo Code of Conduct) · `collab@` · `press@` · `sponsor@`. Không dùng `games@` cho dự án này.
---
## 9. Forge & CI
- **Gitea** (`https://git.poli0981.dev`, Gitea 28.x) là nhà chính; remote `origin` = Gitea (SSH cổng 2222), `github` = remote cũ (tài khoản bị khóa — **không bao giờ push/xóa**). Mirror công khai GitLab nhận issue/MR; registration của Gitea đóng. Runbook di chuyển: `E:\.github\docs\GITEA-MIGRATION.md` (repo ops `poli0981/.github`).
- CI = **Gitea Actions** trong `.gitea/workflows/` (không còn `.github/workflows`). Runner là PC của maintainer: `windows-latest` = host mode (PowerShell, không cô lập; `setup-dotnet` cài vào tool cache), `ubuntu-latest` = Docker. Cron chỉ trong 13:00–16:00 UTC, phút lẻ, slot đăng ký trong `docs/migration/README.md` của repo ops (CommandForge: `Security` thứ Sáu 14:11 UTC).
- Workflow dùng chung từ repo ops, **pin theo SHA của tag ops** (`# ops vYYYY.MM.N`) kèm `ops_ref` cùng SHA; Renovate không bump các pin này — bump tay khi repo ops có tag mới. Mọi action bên thứ ba pin SHA 40 ký tự + comment version. Upload artifact bằng `christopherhx/gitea-upload-artifact`.
- Không có trên Gitea: CodeQL, Dependabot, SonarCloud, Scorecard, dependency review, attestations/OIDC, GitHub Pages/Discussions/Releases, `gh` CLI (dùng Gitea REST API với job token). Thay bằng: Qodana (CLI), `security.yml` (gitleaks, Opengrep, osv-scanner, NuGetAudit, actionlint), Renovate (`renovate.json` + preset `poli0981/renovate-config`).
- Bí mật phát hành (`R2_RELEASES_*`, biến `R2_ACCOUNT_ID`, cấp user) chỉ dùng trong `release.yml` (tag/dispatch), qua biến môi trường `VPK_*`, không bao giờ trên dòng lệnh hay trong job `pull_request`/schedule.
+25 -1
View File
@@ -1,6 +1,6 @@
# Disclaimer — CommandForge
> Last updated: 2026-06-18. This is not legal advice.
> Last updated: 2026-10-21. This is not legal advice.
## ⚠️ Use at your own risk
@@ -52,3 +52,27 @@ please report translation problems via an issue.
Command descriptions and documentation are provided in good faith but **may be incomplete or
out of date** for some Windows versions. Command behavior can differ between Windows 10 and 11
and across OS updates.
## Copyright and takedown requests
CommandForge's code and documentation are © poli0981 and contributors, licensed under the GPLv3.
Third-party components keep their own licenses (see
[THIRD-PARTY-NOTICES.md](THIRD-PARTY-NOTICES.md)). If you believe something in this project
infringes your rights, please contact us first so it can be corrected quickly:
- **Copyright questions** (attribution, licensing, permission requests):
[copyright@poli0981.dev](mailto:copyright@poli0981.dev)
- **DMCA notices:** [dmca@poli0981.dev](mailto:dmca@poli0981.dev). Include the details required by
17 U.S.C. § 512(c)(3): the work, the material you believe infringes it and its location (URL),
your contact details, a good-faith statement, a statement that the notice is accurate and that
you are authorized to act, and your signature.
- **Other takedown requests** (trademark, impersonation, unlawful content):
[takedown@poli0981.dev](mailto:takedown@poli0981.dev)
The source is hosted on the maintainer's own server (`git.poli0981.dev`), so these addresses are
the way to reach the project. For content on its public mirror on GitLab, GitLab's own DMCA
process also applies.
## Contact
Other legal questions: [legal@poli0981.dev](mailto:legal@poli0981.dev).
+25 -3
View File
@@ -21,6 +21,18 @@
don't force XML docs on every public member. -->
<GenerateDocumentationFile>true</GenerateDocumentationFile>
<NoWarn>$(NoWarn);CS1591</NoWarn>
<!-- Supply-chain audit: restore checks direct AND transitive packages against the GitHub
Advisory Database. Moderate+ advisories (NU1902-NU1904) fail the build through
TreatWarningsAsErrors; low-severity ones (NU1901) stay warnings. -->
<NuGetAudit>true</NuGetAudit>
<NuGetAuditMode>all</NuGetAuditMode>
<NuGetAuditLevel>low</NuGetAuditLevel>
<WarningsNotAsErrors>$(WarningsNotAsErrors);NU1901</WarningsNotAsErrors>
<!-- Normalized source paths in PDBs for CI builds (reproducible artifacts). Gitea Actions sets
GITHUB_ACTIONS=true too, for compatibility. -->
<ContinuousIntegrationBuild Condition="'$(GITHUB_ACTIONS)' == 'true'">true</ContinuousIntegrationBuild>
</PropertyGroup>
<!--
@@ -39,10 +51,20 @@
<Company>poli0981</Company>
<Copyright>Copyright © 2026 poli0981</Copyright>
<Description>Run complex Windows system commands through a visual, categorized interface.</Description>
<RepositoryUrl>https://github.com/poli0981/CommandForge</RepositoryUrl>
<PackageProjectUrl>https://github.com/poli0981/CommandForge</PackageProjectUrl>
<RepositoryUrl>https://git.poli0981.dev/poli0981/CommandForge</RepositoryUrl>
<PackageProjectUrl>https://git.poli0981.dev/poli0981/CommandForge</PackageProjectUrl>
<RepositoryType>git</RepositoryType>
<Version>1.0.0</Version>
<Version>2.3.0</Version>
</PropertyGroup>
<!-- Sonar's C# rules as a Roslyn analyzer, enforced at build time (warnings are errors). Package
versions live in each .csproj, not in Directory.Packages.props (the project's convention;
Renovate and the CycloneDX SBOM read them there). -->
<ItemGroup>
<PackageReference Include="SonarAnalyzer.CSharp" Version="10.37.0.15768">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
</ItemGroup>
</Project>
+10 -4
View File
@@ -1,6 +1,6 @@
# Terms of Use (EULA) — CommandForge
> Not legal advice. Last updated: 2026-06-18 · Version 1.1
> Not legal advice. Last updated: 2026-10-21 · Version 1.1
>
> ⚠️ **Important:** CommandForge is licensed under the **GNU GPL v3** (see [LICENSE](LICENSE)).
> **The GPLv3 governs your rights to the software.** This document does **not** restrict any
@@ -40,9 +40,9 @@ the use of, or inability to use, the software. (Consistent with **GPLv3 §16**.)
## 5. Acceptable use
- Use the software in compliance with all applicable laws in your jurisdiction, and in compliance
with the [GitHub Terms of Service](https://docs.github.com/site-policy/github-terms/github-terms-of-service)
when interacting with the project on GitHub.
- Use the software in compliance with all applicable laws in your jurisdiction, and with the
terms of the site you use when interacting with the project (for example GitLab's, for issues
and merge requests on its mirror).
- Use it only to administer **your own computers** or machines you are authorized to administer.
- Do **not** use the software to damage, disrupt, defraud, or otherwise act unlawfully, or to
violate the rights or privacy of others (including data-protection laws such as the GDPR and
@@ -58,3 +58,9 @@ trademark owner mentioned. All trademarks belong to their respective owners. See
By installing and using the software, you acknowledge that you have read, understood, and agree to
this document and to the terms of the GPLv3.
## 8. Contact
Questions about these terms or licensing: **[legal@poli0981.dev](mailto:legal@poli0981.dev)**.
For copyright, DMCA and other takedown notices, see
[DISCLAIMER.md](DISCLAIMER.md#copyright-and-takedown-requests).
+4 -1
View File
@@ -2,7 +2,10 @@
CommandForge is currently maintained by:
- [@poli0981](https://github.com/poli0981) — author & maintainer
- [poli0981](https://git.poli0981.dev/poli0981) — author & maintainer
Contact: [code@poli0981.dev](mailto:code@poli0981.dev) for the code and contributions; see the
[README](README.md#contact) for the other addresses (security, privacy, legal…).
Want to help maintain the project? Start by contributing (see
[CONTRIBUTING.md](.github/CONTRIBUTING.md)); active, trusted contributors may be invited.
+41 -22
View File
@@ -1,41 +1,60 @@
# Privacy Policy — CommandForge
> This is a plain-language summary, not legal advice. Last updated: 2026-06-18.
> This is a plain-language summary, not legal advice. Last updated: 2026-11-26.
## Summary
**CommandForge does not collect, store on any server, or transmit any of your personal data.**
The app runs entirely **locally** on your machine. The **only** network connection it makes is
to GitHub, to check for and download software updates.
The app runs entirely **locally** on your machine. The **only** network connection the app itself
makes is to `releases.poli0981.dev`, to check for and download software updates.
## Data processed locally (never leaves your machine)
## Data stored on your PC (never leaves your machine)
| Data | Location | Purpose |
|---|---|---|
| Settings (theme, language, font size, favorites, window placement, accepted-terms version) | `%AppData%\CommandForge\config.json` | Remember your preferences |
| Application logs | `%AppData%\CommandForge\logs\` | Local troubleshooting |
| Reports you generate (e.g. exported logs) | A folder you choose | Only when you ask for them |
| Settings: theme, language, font size, safety and behavior options, log level, favorites, recent commands, window size and position, accepted-terms version | `%AppData%\CommandForge\config.json` | Remember your preferences |
| Execution history: command ID, time, exit code, result, duration | `%AppData%\CommandForge\history.json` | The History page, Run again and Undo |
| Recipes you create | `%AppData%\CommandForge\recipes.json` | Your saved command chains |
| Commands you add under *My commands* | `%AppData%\CommandForge\user-commands.json` | Your own commands |
| Saved settings profiles | `%AppData%\CommandForge\profiles.json` | Switching between profiles |
| Application logs (at most 14 daily files of up to 10 MB each) | `%AppData%\CommandForge\logs\` | Local troubleshooting |
| Backups of damaged files (`*.corrupt-<timestamp>.json`) | `%AppData%\CommandForge\` | So a damaged file is never silently lost |
| Files you export: settings, logs (`.zip`), console output | A location you choose | Only when you ask for them |
| The program itself | `%LocalAppData%\CommandForge\` | Installed app files (Velopack) |
This data stays on your device and is never sent to us or any third party.
This data stays on your device and is never sent to us or to any third party. The history stores
command IDs and results, not command output.
**Logs** record app events, errors, and a one-line summary of each command you run (its ID, exit
code and duration). They don't contain the commands' output, but they may contain machine-specific
details such as file paths, your user name or device names.
## Network connections
- **Update check:** the app contacts **GitHub** (releases API + asset download) to see whether a
newer version exists and to fetch it. This is subject to
[GitHub's Privacy Statement](https://docs.github.com/site-policy). We receive no identifying
data from it.
- The app makes **no other network connections**.
- **Update check:** the app downloads the update feed (and, when you choose to update, the
update package) from **`releases.poli0981.dev`** when it starts, if *Check for updates on
startup* is on (the default), and whenever you choose **Check for updates** (`F5`). The files
are stored on Cloudflare R2 and served by Cloudflare, which sees your IP address and the request
like any web server; see [Cloudflare's Privacy Policy](https://www.cloudflare.com/privacypolicy/).
The project keeps no logs of these downloads and receives no data from them. (Versions 2.2.0
and older contacted GitHub instead.)
- **Links you open** — the source code on `git.poli0981.dev`, the user guide, the license,
*Report a bug* on GitLab — open in your browser, under those sites' own policies.
- The app makes **no other network connections**. Some **commands you choose to run** use the
network by their nature (for example winget, DNS and connectivity tests, Windows Update); that
traffic goes between Windows and those services, not to us.
## No telemetry / analytics
CommandForge contains **no** telemetry, analytics, advertising, or behavioral tracking of any kind.
CommandForge contains **no** telemetry, analytics, advertising, crash uploading, or behavioral
tracking of any kind.
## Commands you run
## Bug reports
When you run a command, its output is shown in the app and may be written to the **local** log
for troubleshooting. This output is never sent anywhere. If you export logs to file a bug report,
**review the contents yourself before sharing** — logs may include machine-specific details
(paths, device names) you may not wish to publish.
*Report a bug* opens a pre-filled issue on the project's GitLab mirror in your browser with the app version, your
Windows version and, after a crash, the error details. **Nothing is sent until you submit the form
yourself**, and you can edit it first. If you attach exported logs, **review them before sharing**
— they may include paths, user names or device names you may not wish to publish.
## Children
@@ -49,6 +68,6 @@ to review the terms again on startup.
## Contact
- Repository: https://github.com/poli0981/CommandForge
- Questions: open an issue, or use private vulnerability reporting for security matters
(see [SECURITY.md](.github/SECURITY.md)).
- Privacy questions: **[privacy@poli0981.dev](mailto:privacy@poli0981.dev)**
- Security issues: see [SECURITY.md](.github/SECURITY.md) (security@poli0981.dev).
- Repository: https://git.poli0981.dev/poli0981/CommandForge (issues: https://gitlab.com/poli0981/CommandForge/-/issues)
+122 -34
View File
@@ -1,66 +1,127 @@
# CommandForge
[![Latest release](https://img.shields.io/gitea/v/release/poli0981/CommandForge?gitea_url=https%3A%2F%2Fgit.poli0981.dev&sort=semver)](https://git.poli0981.dev/poli0981/CommandForge/releases)
[![Status: stable, maintenance only](https://img.shields.io/badge/status-stable%20%C2%B7%20maintenance%20only-blue)](#project-status)
[![Build status](https://git.poli0981.dev/poli0981/CommandForge/actions/workflows/build.yml/badge.svg?branch=main)](https://git.poli0981.dev/poli0981/CommandForge/actions?workflow=build.yml)
[![Security status](https://git.poli0981.dev/poli0981/CommandForge/actions/workflows/security.yml/badge.svg?branch=main)](https://git.poli0981.dev/poli0981/CommandForge/actions?workflow=security.yml)
[![Qodana status](https://git.poli0981.dev/poli0981/CommandForge/actions/workflows/qodana.yml/badge.svg?branch=main)](https://git.poli0981.dev/poli0981/CommandForge/actions?workflow=qodana.yml)
[![Accessibility: WCAG 2.2 AA target](https://img.shields.io/badge/accessibility-WCAG%202.2%20AA%20target-2ea44f)](ACCESSIBILITY.md)
![Platform: Windows 10 and 11](https://img.shields.io/badge/platform-Windows%2010%20%7C%2011-0078D6)
[![License: GPL v3](https://img.shields.io/badge/license-GPL--3.0-blue)](LICENSE)
> Run powerful Windows maintenance commands from a clean, categorized GUI — no need to
> memorize syntax.
> **Where things live** (since November 2026, when the GitHub account was suspended): source at
> [`git.poli0981.dev/poli0981/CommandForge`](https://git.poli0981.dev/poli0981/CommandForge) (canonical). Mirror for issues and merge
> requests: [`gitlab.com/poli0981/CommandForge`](https://gitlab.com/poli0981/CommandForge).
> Downloads and updates: [`releases.poli0981.dev/commandforge/`](#install). Patches and questions:
> `code@poli0981.dev`. Security: `security@poli0981.dev` (see [SECURITY.md](.github/SECURITY.md)).
CommandForge is an open-source Windows desktop app that wraps common system commands
(winget, DISM, SFC, God Mode, registry tweaks, network reset, power plans, diagnostics…)
in a visual, categorized interface. Every command is shown to you **before** it runs, with a
clear danger level, optional confirmation, and an optional System Restore Point.
clear danger level, a confirmation for anything risky, and an optional System Restore Point.
- **Windows 10 (22H2) and Windows 11**, x64.
- **Open source, GPLv3.**
- **Offline-first. No telemetry.** The only network call is to GitHub to check for updates.
- **Offline-first. No telemetry.** The only network connection the app makes is the update
check, to `releases.poli0981.dev`.
- Installed and auto-updated with [Velopack](https://velopack.io/) (per-user, no UAC for updates).
> **Status:** pre‑1.0. Built by a solo developer with AI assistance (see
> [Disclaimer](DISCLAIMER.md) and the AI disclosure below).
> Built by a solo developer with AI assistance — see the [Disclaimer](DISCLAIMER.md) and the
> AI disclosure below.
---
## Project status
**Stable, maintenance only** since version 2.2.0 (November 2026). CommandForge does what it set
out to do, so the work now goes into keeping it secure, correct and accessible: dependency and
security updates (a High or Critical vulnerability gets an urgent patch release), major platform
updates such as a newer .NET, catalog commands added, fixed or removed, bug, UI/UX and
accessibility fixes, and translation fixes. A new feature is added only when it is genuinely
necessary. The whole policy is in
[CONTRIBUTING.md](.github/CONTRIBUTING.md#maintenance-mode-what-we-accept).
---
## Features
- **Categorized command catalog** — browse by group (System & Maintenance, Updates & Packages,
Tweaks & Shortcuts, Network, Cleanup, Power, System Info, Diagnostics, Security & Privacy,
Developer) with fuzzy search and a Command Palette (`Ctrl+K`).
- **Safe by design** — the command catalog is a vetted, read-only embedded resource. The app
never loads arbitrary commands and self-elevates. Admin commands run through a separate
elevation broker (one UAC prompt per session).
- **See before you run** — the exact command line is previewed; `Caution`/`Dangerous` commands
require confirmation (type-to-confirm for `Dangerous`), with an optional Restore Point.
- **Real-time console** — stream output, cancel long-running commands, detect reboot-required
(`exit 3010`).
- **Home dashboard** — recent commands, pinned favorites, and a read-only system-status widget
(Windows build, RAM, system drive, uptime).
- **Polish** — light/dark/system theme, font scaling, live English/Vietnamese switching, a Log
Viewer, a Debug panel, and a global crash handler with a "Report a bug" flow.
- **298 vetted commands in 15 categories** — System & Maintenance, Updates & Packages, Tweaks &
Shortcuts, Network, Cleanup, Power, System Info, Diagnostics, Security & Privacy, Developer,
Storage, Services & Startup, Devices & Peripherals, Backup & Recovery, and Accounts & Sign-in.
Commands that don't apply to your Windows build are hidden.
- **Fluent design** — a Windows 11-style window (Mica, navigation pane, in-window dialogs) that
follows your light/dark theme, accent color and High Contrast. It is resizable and remembers its
size and position.
- **Find anything fast** — accent-insensitive search (`Ctrl+F`), filters by danger level and admin
rights, favorites, and a Command Palette over the whole catalog (`Ctrl+K`).
- **Safe by design** — the catalog is a read-only part of the app, reviewed by the maintainer;
nothing outside it ever runs as administrator. Admin commands run in a separate elevated helper
(one UAC prompt per session, which you can end at any time).
- **See before you run** — the exact command line is previewed with paths filled in. `Caution`
commands ask first; `Dangerous` ones require typing the command's name or ID, and that check
can't be turned off. A System Restore Point can be created first.
- **Live console** — output streams in real time and stays readable on non-English Windows
(UTF-16, UTF-8 and OEM code pages are decoded); cancel, copy, or save it to a file.
Restart-required is detected from the exit code (`3010`).
- **History, undo and recipes** — run past commands again, undo reversible tweaks (with a registry
before/after diff), and chain commands into recipes that confirm every risky step.
- **My commands** — save your own commands. They are kept apart from the catalog and always run
without admin rights.
- **Five languages** — English, Tiếng Việt, 日本語, 简体中文 and Español, switchable without a
restart.
- **Diagnostics** — Log Viewer, Debug panel, local logs with retention, and a crash dialog with a
"Report a bug" flow that never sends anything by itself.
- **Accessible** — everything works with the keyboard alone (`F6` moves between the navigation
pane, the page and the console), Narrator hears what each command does and how it ended, and the
app follows Windows contrast themes and Text size. See [ACCESSIBILITY.md](ACCESSIBILITY.md).
New here? Read the **[user guide](USAGE.md)**.
---
## Install
1. Download the latest **`CommandForge-win-Setup.exe`** from the
[Releases page](https://github.com/poli0981/CommandForge/releases).
2. Run it. The app installs per-user and updates itself from future releases.
1. Download **[`CommandForge-win-Setup.exe`](https://releases.poli0981.dev/commandforge/CommandForge-win-Setup.exe)**
(or the [portable zip](https://releases.poli0981.dev/commandforge/CommandForge-win-Portable.zip)).
Every release, its notes and its checksums are on the [releases page](https://git.poli0981.dev/poli0981/CommandForge/releases).
2. Run it. The app installs per-user (no admin rights needed) and updates itself from future
releases.
### "Unknown publisher" / SmartScreen
Already installed? The app offers each new release as a normal update; your settings, favorites,
history, recipes and commands carry over.
CommandForge is **not code-signed yet** (see [SECURITY.md](.github/SECURITY.md)), so Windows
SmartScreen may warn about an unknown publisher and some antivirus engines may show a false
positive (common for system-administration tools). To proceed: **More info → Run anyway**.
> **Coming from 2.2.0 or older?** Those versions checked GitHub for updates, and the GitHub account
> is gone, so they will never see a new version. Download the installer above once and run it over
> your installation: your data stays, and from 2.3.0 on updates come from `releases.poli0981.dev`.
To verify your download, compare its SHA-256 against the `checksums.txt` attached to the release,
and review the VirusTotal link in the release notes:
### "Unknown publisher" and verifying your download
```powershell
Get-FileHash .\CommandForge-win-Setup.exe -Algorithm SHA256
```
CommandForge is **not Authenticode-signed yet** (see [SECURITY.md](.github/SECURITY.md)), so
SmartScreen may warn about an unknown publisher, and some antivirus engines may flag it (common
for system-administration tools). To proceed: **More info → Run anyway**.
Every release is built by the release workflow on Gitea Actions from a signed tag, and its log is
public. You can check your download first:
- **SHA-256** — compare with `SHA256SUMS` of that release
(`https://releases.poli0981.dev/commandforge/<version>/SHA256SUMS`, linked from the release
notes; case doesn't matter):
```powershell
(Get-FileHash .\CommandForge-win-Setup.exe -Algorithm SHA256).Hash
```
- Each release ships a CycloneDX **SBOM** (`sbom.cdx.json`, next to `SHA256SUMS`), and the release
notes link a **VirusTotal** scan when one was made.
---
## Build from source
Requires the **.NET 10 SDK** on Windows 10 22H2 / 11.
Requires Windows 10 22H2 / 11 and the **.NET 10 SDK** (the exact band is pinned in `global.json`).
```bash
dotnet restore
@@ -69,8 +130,7 @@ dotnet run --project src/CommandForge.Wpf
dotnet test
```
See [BUILD.md](BUILD.md) for publish/packaging and [UPDATES.md](UPDATES.md) for how the
Velopack update mechanism works.
See [BUILD.md](BUILD.md) for packaging and CI, and [UPDATES.md](UPDATES.md) for how updates work.
---
@@ -78,15 +138,43 @@ Velopack update mechanism works.
| Topic | File |
|---|---|
| User guide | [USAGE.md](USAGE.md) |
| Accessibility | [ACCESSIBILITY.md](ACCESSIBILITY.md) |
| Release history | [CHANGELOG.md](CHANGELOG.md) |
| Build, test, publish, release | [BUILD.md](BUILD.md) · [RELEASING.md](RELEASING.md) |
| Update mechanism (Velopack) | [UPDATES.md](UPDATES.md) |
| Contributing & contribution rules | [CONTRIBUTING.md](.github/CONTRIBUTING.md) |
| Contributing | [CONTRIBUTING.md](.github/CONTRIBUTING.md) |
| Security policy & disclosure | [SECURITY.md](.github/SECURITY.md) |
| Privacy policy | [PRIVACY.md](PRIVACY.md) |
| Disclaimer | [DISCLAIMER.md](DISCLAIMER.md) |
| Terms of use (EULA) | [EULA.md](EULA.md) |
| Third-party notices | [THIRD-PARTY-NOTICES.md](THIRD-PARTY-NOTICES.md) |
| Code of Conduct | [CODE_OF_CONDUCT.md](.github/CODE_OF_CONDUCT.md) |
| Maintainers | [MAINTAINERS.md](MAINTAINERS.md) |
---
## Contact
Bugs, catalog commands, translations and accessibility problems go to the issues of the
[GitLab mirror](https://gitlab.com/poli0981/CommandForge/-/issues) (pick the matching template;
see [Project status](#project-status) for what is accepted). The repository on Gitea is read-only
for everyone but the maintainer. Patches can also come by e-mail (`git format-patch`) to
code@poli0981.dev. For everything else:
| Topic | Address |
|---|---|
| Security vulnerabilities (private, never a public issue) | security@poli0981.dev |
| Accessibility barriers | accessibility@poli0981.dev, or the [Accessibility template](https://gitlab.com/poli0981/CommandForge/-/issues/new?issuable_template=Accessibility) on GitLab |
| Privacy | privacy@poli0981.dev |
| Terms, licensing and other legal questions | legal@poli0981.dev |
| Copyright questions and permissions | copyright@poli0981.dev |
| DMCA notices | dmca@poli0981.dev |
| Other takedown requests (trademark, impersonation, unlawful content) | takedown@poli0981.dev |
| Code, contributions and Code of Conduct reports | code@poli0981.dev |
| Collaboration | collab@poli0981.dev |
| Press | press@poli0981.dev |
| Sponsorship | sponsor@poli0981.dev |
---
+67 -36
View File
@@ -1,50 +1,81 @@
# Releasing CommandForge
Releases are automated by [`release.yml`](.github/workflows/release.yml), triggered by pushing a
SemVer tag.
Releases are automated by [`release.yml`](.gitea/workflows/release.yml) on Gitea Actions,
triggered by pushing a signed SemVer tag. The files go to Cloudflare R2
(`https://releases.poli0981.dev/commandforge/`), the notes and links to a release on
[Gitea](https://git.poli0981.dev/poli0981/CommandForge/releases). The forge itself stores no
binaries.
## Steps
1. Update `docs/Changelog.md` (internal) and make sure `main` is green.
2. Choose a SemVer version `X.Y.Z`.
3. Tag and push:
1. Make sure `main` is green and contains everything for the release.
2. Choose a SemVer version `X.Y.Z`. In a pull request, move the `[Unreleased]` notes in
[CHANGELOG.md](CHANGELOG.md) under `## [X.Y.Z] — <date>`, add the compare link at the bottom,
and set `<Version>` in `Directory.Build.props` to `X.Y.Z` (the workflow refuses a tag that
doesn't match it). Merge it.
3. Optional dry run: **Actions → Release → Run workflow** on `main`. It builds, packs, writes the
SBOM, checksums and notes, and reads the previous release from R2 (which checks the R2
credentials), but uploads nothing; the files stay as the run's `r2-release` artifact.
4. Tag the merge commit on `main` with a **signed, annotated** tag and push it:
```bash
git tag v0.3.0
git push origin v0.3.0
git switch main && git pull
git tag -s vX.Y.Z -m "CommandForge X.Y.Z"
git push origin vX.Y.Z
```
4. The **Release** workflow runs on `windows-latest` and:
- resolves the version from the tag (`vX.Y.Z` → `X.Y.Z`),
- installs `vpk`,
- **downloads the previous release** (`vpk download github`) so a delta can be computed
(skipped/ignored on the very first release),
- publishes self-contained and packages with Velopack (`scripts/pack.ps1`, which stamps the
assembly version),
- **publishes the GitHub Release** with all `Releases/` assets (`vpk upload github --publish`),
- generates **`checksums.txt`** (SHA-256) and attaches it,
- if `VT_API_KEY` is set, submits `Setup.exe` + `*-full.nupkg` to **VirusTotal** and appends the
scan links to the release notes.
5. Edit the GitHub Release notes if needed (changelog highlights). The SHA-256 + VirusTotal info is
already attached.
You can also run the workflow manually (**Actions → Release → Run workflow**) with a `version`
input; it tags `vX.Y.Z` via the upload step.
5. The **Release** workflow runs on the Windows runner (host mode on the maintainer's PC) and:
- checks that the tag matches `<Version>`;
- restores the pinned tools (`vpk`, CycloneDX) and **downloads the previous release** from R2
(`vpk download s3`) so a delta package can be computed;
- publishes and packages with Velopack (`scripts/pack.ps1`);
- writes the **CycloneDX SBOM**, **`SHA256SUMS`** and the release notes (this version's section
of `CHANGELOG.md` plus the download links) with `scripts/release-assets.ps1`;
- if `VT_API_KEY` is set, submits `Setup.exe` and the full package to **VirusTotal** and adds
the report links to the notes;
- uploads to R2 with `vpk upload s3`: packages, installer and portable zip first, the feed
(`releases.win.json`, `RELEASES`) last, keeping the ten newest releases; installed copies see
the update from that moment;
- checks that the feed, the installer, the portable zip and the full package answer `200`;
- puts `SHA256SUMS` and `sbom.cdx.json` under `commandforge/X.Y.Z/` (the ops repo's
`publish-r2.yml`; a file there is never overwritten);
- creates the Gitea release `vX.Y.Z` with the notes and the links;
- calls the shared announcer (`poli0981/.github`) to post the release to Discord.
6. Check the [release page](https://git.poli0981.dev/poli0981/CommandForge/releases) and the
files, for example:
## Required repository secrets
```powershell
curl.exe -sI https://releases.poli0981.dev/commandforge/releases.win.json
curl.exe -s https://releases.poli0981.dev/commandforge/X.Y.Z/SHA256SUMS
```
| Secret | Used for | Required |
|---|---|---|
| `GITHUB_TOKEN` | Create the release & upload assets | automatic |
| `VT_API_KEY` | VirusTotal scan + links | optional (step skipped if unset) |
| `DISCORD_RELEASES_WEBHOOK` (or `DISCORD_REPO_WEBHOOK`) | Release announcement to Discord | optional |
| `DISCORD_PING_ROLE_ID` | Role ping on stable releases | optional |
| `DISCORD_CI_WEBHOOK` | Build-failure alerts to Discord | optional |
Edit the notes on the release page if you want a shorter summary (keep the download links,
the checksums and the VirusTotal section).
> `poli0981` is a user account (not an org), so secrets are set **per repository**
> (Settings → Secrets and variables → Actions).
A versioned file on R2 is never replaced. If a release fails after its packages were uploaded,
fix the cause and release the next patch version rather than re-tagging.
## Secrets and variables
| Name | Kind | Where | Used for |
|---|---|---|---|
| `R2_RELEASES_ACCESS_KEY_ID`, `R2_RELEASES_SECRET_ACCESS_KEY` | secret | user level (Gitea → Settings → Actions) | `vpk download/upload s3` and `publish-r2.yml`: an R2 API token with Object Read & Write on `poli0981-releases` only |
| `R2_ACCOUNT_ID` | variable | user level | The R2 endpoint (`https://<id>.r2.cloudflarestorage.com`) |
| `GITEA_TOKEN` (`github.token`) | automatic | | Create the Gitea release; read it for the announcement |
| `VT_API_KEY` | secret | repository | VirusTotal scan + links (optional; skipped if unset) |
| `DISCORD_RELEASES_WEBHOOK` (or `DISCORD_REPO_WEBHOOK`) | secret | repository | Release announcement to Discord |
| `DISCORD_PING_ROLE_ID` | secret | repository | Role ping on stable releases (optional) |
| `DISCORD_RELEASE_PIPELINE_WEBHOOK` | secret | repository | Result of every Release run |
| `DISCORD_CI_WEBHOOK` | secret | repository | Build / Qodana / Security failures on `main` |
| `QODANA_TOKEN` | secret | repository | Qodana Cloud project token; selects the Ultimate licence (`qodana.yml`) |
Release credentials are only ever used by `release.yml`, which runs on a tag or a manual
dispatch, never on a pull request or a schedule.
## Code signing
Not done yet. Releases ship unsigned; users may see a SmartScreen "unknown publisher" warning.
Mitigations: SHA-256 + VirusTotal (above), no obfuscation, public source. When Azure Trusted
Signing (or SignPath Foundation) is configured, add a signing step after `dotnet publish` and
before `vpk pack`, and update [SECURITY.md](.github/SECURITY.md).
Not done yet: releases ship without an Authenticode signature, so users may see a SmartScreen
"unknown publisher" warning. Mitigations: SHA-256 checksums, an SBOM, VirusTotal, public build
logs, no obfuscation, and public source. When Azure Trusted Signing (or SignPath Foundation) is
configured, add a signing step between `dotnet publish` and `vpk pack` in `scripts/pack.ps1`, and
update [SECURITY.md](.github/SECURITY.md).
+26 -17
View File
@@ -1,29 +1,38 @@
# Third-Party Notices
CommandForge (licensed under GPLv3) bundles or depends on the third-party components below.
Each remains under its own license; all are compatible with GPLv3. Versions reflect the current
build — see the `.csproj` files for the authoritative versions.
Each remains under its own license; every component shipped with the app is compatible with
GPLv3. Versions reflect the current build — see the `.csproj` files for the authoritative
versions.
## NuGet packages (runtime)
## NuGet packages shipped with the app
| Component | Version | License | Project |
|---|---|---|---|
| MaterialDesignThemes (+ MaterialDesignColors) | 5.3.2 | MIT | https://github.com/MaterialDesignInXAML/MaterialDesignInXamlToolkit |
| WPF-UI (+ WPF-UI.Abstractions) | 4.3.0 | MIT | https://github.com/lepoco/wpfui |
| CommunityToolkit.Mvvm | 8.4.2 | MIT | https://github.com/CommunityToolkit/dotnet |
| Microsoft.Extensions.Hosting | 10.0.9 | MIT | https://github.com/dotnet/runtime |
| Microsoft.Extensions.DependencyInjection.Abstractions | 10.0.9 | MIT | https://github.com/dotnet/runtime |
| Serilog | 4.3.1 | Apache-2.0 | https://github.com/serilog/serilog |
| Serilog.Extensions.Hosting | 10.0.0 | Apache-2.0 | https://github.com/serilog/serilog-extensions-hosting |
| Microsoft.Extensions.DependencyInjection (+ .Abstractions) | 10.0.15 | MIT | https://github.com/dotnet/runtime |
| Serilog | 4.4.0 | Apache-2.0 | https://github.com/serilog/serilog |
| Serilog.Sinks.File | 7.0.0 | Apache-2.0 | https://github.com/serilog/serilog-sinks-file |
| Serilog.Sinks.Async | 2.1.0 | Apache-2.0 | https://github.com/serilog/serilog-sinks-async |
| Velopack | 1.2.0 | MIT | https://github.com/velopack/velopack |
| System.Text.Json | (bundled with .NET 10) | MIT | https://github.com/dotnet/runtime |
| Velopack (library, installer and update helpers) | 1.2.161 | MIT | https://github.com/velopack/velopack |
| System.Text.Json and the rest of the .NET libraries | (bundled with .NET 10) | MIT | https://github.com/dotnet/runtime |
## Build-time only (not redistributed)
WPF-UI incorporates code from VirtualizingWrapPanel, dotnet/wpf and microsoft-ui-xaml (all MIT)
and the Fluent System Icons (below); see the `ThirdPartyNotices.txt` in the WPF-UI package.
## Build and test tools (not redistributed)
| Component | Version | License | Project |
|---|---|---|---|
| Microsoft.Windows.CsWin32 | 0.3.296 | MIT | https://github.com/microsoft/CsWin32 |
| Microsoft.Windows.CsWin32 | 0.3.371 | MIT | https://github.com/microsoft/CsWin32 |
| SonarAnalyzer.CSharp | 10.37.0.15768 | SONAR Source-Available License v1.0 | https://github.com/SonarSource/sonar-dotnet |
| CycloneDX module for .NET (release SBOM only) | 6.3.2 | Apache-2.0 | https://github.com/CycloneDX/cyclonedx-dotnet |
| vpk (Velopack CLI) | 1.2.161 | MIT | https://github.com/velopack/velopack |
| xunit.v3 (`xunit.v3.mtp-off`) | 4.0.3 | Apache-2.0 | https://github.com/xunit/xunit |
| xunit.runner.visualstudio | 4.0.1 | Apache-2.0 | https://github.com/xunit/visualstudio.xunit |
| Microsoft.NET.Test.Sdk | 18.12.0 | MIT | https://github.com/microsoft/vstest |
| coverlet.collector | 10.1.1 | MIT | https://github.com/coverlet-coverage/coverlet |
## Runtime & platform
@@ -31,11 +40,11 @@ build — see the `.csproj` files for the authoritative versions.
## Fonts & icons
- **Material Design Icons** (via MaterialDesignThemes `PackIcon`) — Apache-2.0 / SIL OFL 1.1 —
https://github.com/Templarian/MaterialDesign
- **Cascadia Code / Cascadia Mono** (console/monospace, referenced by name with fallbacks; not
bundled) — SIL OFL 1.1 — https://github.com/microsoft/cascadia-code
- **Segoe UI / Segoe UI Variable** — Windows system font (not bundled).
- **Fluent System Icons** (bundled inside WPF-UI; used for every icon in the app) — MIT,
© Microsoft Corporation — https://github.com/microsoft/fluentui-system-icons
- **Cascadia Mono** (console and code text, referenced by name with Consolas / Courier New
fallbacks; not bundled) — SIL OFL 1.1 — https://github.com/microsoft/cascadia-code
- **Segoe UI Variable / Segoe UI** — Windows system fonts (not bundled).
## AI disclosure
+59 -27
View File
@@ -5,43 +5,75 @@ CommandForge installs and updates itself with [Velopack](https://velopack.io/).
## For users
1. Download `CommandForge-win-Setup.exe` from the
[latest release](https://github.com/poli0981/CommandForge/releases) and run it. It installs
per-user under `%LocalAppData%\CommandForge`.
2. After that, the app checks GitHub Releases for newer versions (on startup if enabled, or via
**Help → Check for updates** / `F5`) and updates itself. When a newer version exists it downloads
the update (a small **delta** when possible) and applies it on restart.
1. Download [`CommandForge-win-Setup.exe`](https://releases.poli0981.dev/commandforge/CommandForge-win-Setup.exe)
and run it. It installs per-user under `%LocalAppData%\CommandForge`. The
[releases page](https://git.poli0981.dev/poli0981/CommandForge/releases) lists every version
with its notes and checksums.
2. After that, the app checks `https://releases.poli0981.dev/commandforge` for newer versions — on
startup if **Settings → Updates → Check for updates on startup** is on (the default), or when
you choose **More (⋯) → Check for updates** or press `F5`.
3. When a newer version exists, choose **Download & restart**. The app downloads the update (a
small **delta** when possible), then restarts into the new version.
The only network connection involved is to GitHub (see [PRIVACY.md](PRIVACY.md)). Update errors are
mapped to clear messages: offline, not found (404), rate limited (403/429), and server error (5xx).
> **Versions 2.2.0 and older** checked GitHub Releases. The GitHub account behind the project was
> suspended in November 2026, so those versions find nothing (the check ends with "No release feed
> was found") and can't update themselves. Install 2.3.0 or later once by hand, over the old
> version: settings, favorites, history, recipes and your commands stay where they are.
Good to know:
- Closing the update dialog — including with its **X** button — cancels the download.
- The app never restarts in the middle of a command: if one is running, finish or cancel it first.
If you start a command while the update downloads, the restart waits; choose **Download &
restart** again when the command is done.
- Before applying an update, the app ends the admin session, because the elevated helper runs
from the folder that Velopack replaces.
- Errors are shown in plain words: offline or timed out, no release feed found (404), the update
server refused or rate-limited the request (403/429), and a server error (5xx).
The only network connection involved is to `releases.poli0981.dev` (see [PRIVACY.md](PRIVACY.md)).
## How it works under the hood
- The app calls `VelopackApp.Build().Run()` at startup to handle install/update/uninstall hooks.
- It checks for updates via `UpdateManager(new GithubSource("https://github.com/poli0981/CommandForge", null, prerelease: false))`.
- Auto-update only works for an **installed** build (not a dev/portable run); the app detects this
and hides update prompts otherwise.
- `Program.Main` calls `VelopackApp.Build().Run()` before WPF starts, to handle the
install/update/uninstall hooks.
- The app checks for updates via `new UpdateManager("https://releases.poli0981.dev/commandforge")`
(`ProductLinks.UpdateFeed`): Velopack's HTTP source reads `releases.win.json` there and downloads
the packages it lists from the same folder. No token, no API.
- The folder is a Cloudflare R2 bucket served through Cloudflare. The feed files
(`releases.win.json`, `RELEASES`) and the stable-named installer and portable zip bypass the
edge cache; every other file name carries its version and is never overwritten.
- Download and apply are separate steps, so the app can end the admin session and check for a
running command just before it restarts.
- Auto-update works for the installed app and for the portable zip (both carry Velopack's
`Update.exe`). A build you run from source can't update; the app detects this and says so
instead of offering an update.
## Release artifacts and the delta mechanism
## Release files and the delta mechanism
Each release (see [RELEASING.md](RELEASING.md)) uploads the contents of `Releases/`:
Each release (see [RELEASING.md](RELEASING.md)) puts these files under
`https://releases.poli0981.dev/commandforge/`:
| Asset | Purpose |
| File | Purpose |
|---|---|
| `CommandForge-win-Setup.exe` | First-time installer |
| `CommandForge-win-Setup.exe` | First-time installer (always the newest release) |
| `CommandForge-win-Portable.zip` | The app without an installer; extract it anywhere and it updates itself in place (settings and logs still go to `%AppData%\CommandForge`) |
| `CommandForge-<version>-full.nupkg` | Full package (fallback / first install of a version) |
| `CommandForge-<version>-delta.nupkg` | Delta from the previous version (small download) |
| `releases.win.json` / `RELEASES` | Update manifest the client reads |
| `checksums.txt` | SHA-256 of the assets (manual verification) |
| `releases.win.json` / `assets.win.json` / `RELEASES` | Update manifest the client reads (uploaded last) |
| `<version>/SHA256SUMS` | SHA-256 of what that version ships: installer, portable zip, packages, SBOM |
| `<version>/sbom.cdx.json` | CycloneDX software bill of materials |
**First release (e.g. `v0.3.0`):** there is no previous version, so only a **full** package +
`Setup.exe` + manifest are produced and uploaded.
There is no directory listing: the release notes on the
[releases page](https://git.poli0981.dev/poli0981/CommandForge/releases) link each file. The
feed keeps the ten newest releases.
**Subsequent releases (e.g. `v0.3.1`):** Velopack needs the **previous** `-full.nupkg` present
while packing to compute the delta. The release workflow does this automatically by running
`vpk download github` before `vpk pack`, so each release after the first produces **both** a
`-full.nupkg` and a `-delta.nupkg`. Clients already on `0.3.0` download only the small
`-delta.nupkg`; the full package remains the fallback.
Velopack needs the **previous** `-full.nupkg` present while packing to compute a delta. The
release workflow runs `vpk download s3` before `vpk pack`, so every release after the first one
on R2 produces **both** a `-full.nupkg` and a `-delta.nupkg`; clients on the previous version
download only the delta, and the full package remains the fallback. 2.3.0, the first release on
R2, had no previous version there, so it shipped only a full package.
> If you ever build a release **locally**, run `vpk download github --repoUrl <repo>` first so the
> prior full package is available for the delta — otherwise only a full package is produced.
> If you ever build a release **locally**, run
> `dotnet vpk download http --url https://releases.poli0981.dev/commandforge` first so the prior
> full package is available for the delta — otherwise only a full package is produced.
+284
View File
@@ -0,0 +1,284 @@
# CommandForge user guide
CommandForge runs Windows maintenance commands for you: pick a command, read what it will do, and
run it. This guide covers version 2.2. For installing and verifying downloads, see the
[README](README.md#install).
- [First start](#first-start)
- [The window](#the-window)
- [Finding a command](#finding-a-command)
- [Running a command](#running-a-command)
- [Home](#home)
- [History and undo](#history-and-undo)
- [Recipes](#recipes)
- [My commands](#my-commands)
- [Settings](#settings)
- [Log viewer and Debug panel](#log-viewer-and-debug-panel)
- [Keyboard shortcuts](#keyboard-shortcuts)
- [Accessibility](#accessibility)
- [Updates](#updates)
- [Your data and uninstalling](#your-data-and-uninstalling)
- [Troubleshooting](#troubleshooting)
## First start
The first time you open CommandForge, it asks you to accept its terms:
1. Pick your language in the list above the terms. English, Tiếng Việt, 日本語, 简体中文 and
Español are available, and you can change it later in Settings.
2. Read the summaries on the **EULA**, **GPLv3**, **Disclaimer** and **Privacy** tabs. **Read the
full text online** opens the complete documents.
3. Tick **I have read and agree to all of the terms**, then choose **Continue**.
You'll be asked again only if the terms change.
## The window
- **Title bar**
- The search box, **Search all commands (Ctrl+K)**, opens the Command Palette.
- **Admin session active** appears while administrator commands can run without a new UAC
prompt. Open it to **End admin session**.
- **More (⋯)** holds the Command Palette, **Check for updates**, **Create System Restore
Point**, **Export logs (.zip)**, the config and log folders, **Portable info**, **Keyboard
shortcuts**, **User guide**, **Report a bug**, **Terms & Privacy** and **About CommandForge**.
- **Navigation pane** (left)
- Home, Favorites, History, Recipes and My commands.
- **Command catalog**, with its 15 categories and the number of commands in each.
- Log viewer, Debug panel and Settings, at the bottom.
- `Ctrl+B` shows or hides the pane.
- The window can be resized (down to a minimum size) and maximized. It reopens where you left it.
## Finding a command
- **Browse**: open **Command catalog** or one of its categories. Commands that don't apply to your
version of Windows are hidden.
- **Search**: type in the search box above the list (`Ctrl+F`). Search ignores case and accents
("don dep" finds "Dọn dẹp") and matches titles, descriptions and tags. For everyday phrases such
as "clean disk", a **Did you mean:** suggestion offers the catalog's own word.
- **Filter**: the chips above the list show only **Safe**, **Caution** or **Dangerous** commands,
or **Admin only**. **Clear filters** resets them.
- **Favorites**: select the star on a command to pin it. Pinned commands appear on the
**Favorites** page and on Home.
- **Command Palette** (`Ctrl+K`): search the whole catalog from anywhere. Use `↑`/`↓` to move and
`Enter` to open the command.
## Running a command
Select a command to see its details:
- its description and danger level (**Safe**, **Caution** or **Dangerous**);
- whether it **Requires admin** or **May require restart**;
- the **Estimated time**;
- **Command to run** — the exact command line, with paths filled in. **Copy** copies it.
Choose **Run** to start it. A command that can be undone also shows **Revert**.
### Danger levels and confirmations
| Level | Meaning | Before it runs |
|---|---|---|
| **Safe** | No risk of losing data: read-only queries, opening a tool or settings page, or a small preference change you can undo the same way. | Runs right away. |
| **Caution** | Changes system state (services, registry, caches, boot-time checks). Recoverable, but undoing it may take effort. | Asks you to confirm, unless you turned that off in Settings. |
| **Dangerous** | May lose data, remove a rollback option or leave Windows unstable. | You must type the command's name (or the ID shown) before **Run** appears. This can't be turned off. |
In every confirmation, **Cancel** is the default and `Esc` closes the dialog.
### System Restore Points
For risky administrator commands, the confirmation offers **Create a System Restore Point first
(recommended)**.
- Windows allows only one restore point every 24 hours. If a recent one exists, CommandForge says
it skipped creating a new one.
- If creating it fails, you're asked whether to run the command without one. **No** is the
default.
You can also create one at any time from **More → Create System Restore Point**.
### Administrator commands
The first administrator command of a session shows a Windows UAC prompt for
**CommandForge.Elevator**, and the console shows **Waiting for administrator permission…**.
- If you approve, the elevated helper stays open, so later admin commands run without another
prompt. **Admin session active** appears in the title bar.
- **End admin session** closes the helper when you're done; the next admin command asks again.
- If you decline the prompt, the command doesn't run.
The rest of CommandForge never runs as administrator.
### The console
Output appears live below the details. Drag the splitter to give it more room.
- **Cancel** stops the running command.
- **Copy all output** and **Save output to a file** keep a copy of what it printed.
- When the command ends, the console shows the result (**Success**, **Failed** or **Cancelled**),
the exit code and how long it took.
- Very long output keeps the newest 10,000 lines; a note tells you how many earlier lines aren't
shown.
- Registry tweaks list the affected values before and after the run.
- While a command runs, the taskbar button shows progress. If you moved to another page when it
finishes, a notification tells you the result; if CommandForge is in the background, its
taskbar button also flashes.
### Restarting Windows
When a command reports that a restart is needed (exit code 3010, or a command that always needs
one), the console shows **Restart now**. It asks before restarting and isn't available while a
command is running.
## Home
Home shows:
- **System status**: Windows build, memory, system drive space and uptime.
- **Maintenance suggestions**: for example, Disk Cleanup when the system drive is low on space, or
a restart after a week of uptime. **Open** shows the suggested command.
- Your **Recent commands** and **Favorites**.
## History and undo
**History** lists every command you ran, with the time, result and duration.
- **Run again** repeats a command, with the same confirmations as the first time.
- **Undo** appears for commands that have a vetted revert command (for example, turning a tweak
back off).
- **Clear history** deletes the list after asking.
Run again and Undo are unavailable while another command is running.
## Recipes
A recipe runs several catalog commands in order.
1. Open **Recipes** and choose **New**, then give the recipe a name.
2. Use **Add a command…** and **Add** to append steps. Reorder them with **Move up** and **Move
down**, or use **Remove step**.
3. Choose **Save**, then **Run recipe**.
When a recipe runs:
- You first see an overview of its steps and confirm (**No** is the default).
- Each Caution or Dangerous step then asks exactly as it would on its own.
- If any step is a risky administrator command, a restore point is offered once, before the
first step.
- Administrator steps share one admin session, so you get a single UAC prompt.
- The recipe stops if a step fails, and pauses if a step needs a restart. **Cancel** stops it.
- Steps that aren't available on this PC stay in the recipe but are skipped.
## My commands
Under **My commands** you can save your own command lines, such as a `ping` you run often.
- They are **not part of the vetted catalog** and always run **without administrator rights**.
You alone are responsible for what they do.
- Choose **New**, fill in **Name**, **Executable** (for example `cmd` or `powershell`) and
**Arguments**, then choose **Save**.
- **Run** shows the exact command line and asks before running it.
- With `cmd`, `/c` is added for you, so `cmd` + `ping example.com` runs `cmd /c ping example.com`.
## Settings
| Section | Options |
|---|---|
| **Appearance** | Theme (System, Light, Dark), Language, Font size (Small, Medium, Large; Windows' own Text size enlarges it further). |
| **Behavior & Safety** | Collapse the navigation pane by default; show Admin/Restart badges in lists; confirm before Caution commands; confirm before Dangerous commands (always on); tick "create a restore point" by default for risky admin commands; auto-scroll the console; warn before closing while a command is running. |
| **Updates** | Check for updates on startup, the current version, the last check and **Check now**. |
| **Backup & profiles** | **Export…** / **Import…** your appearance, behavior and favorites as a `.json` file, and save named profiles (for example "Gaming PC" or "Office") that you can **Apply** or **Delete**. |
| **Logs** | Log level, log size, **Open log folder**, **Export logs (.zip)**, **Delete old logs**. |
| **Advanced** | Run mode (whether this copy updates itself), the config folder, the Debug panel, and **Reset to defaults** (keeps your accepted terms and logs). |
| **About** | Version, license and source code links. |
Theme, language and font size change immediately; no restart needed.
## Log viewer and Debug panel
- **Log viewer** (`Ctrl+L`) shows this session's log.
- Filter by level or text, and turn auto-scroll on or off.
- **Open log folder** or **Export logs (.zip)** to share them. Review an export before you share
it.
- **Clear** empties the list shown.
- **Debug panel** has three tabs:
- **Log**: the detailed log.
- **Catalog**: command and category counts, plus any validation errors.
- **System info**: details you can **Copy** into a bug report.
## Keyboard shortcuts
| Keys | Action |
|---|---|
| `Ctrl+K` | Open the Command Palette |
| `Ctrl+F` | Search the current list |
| `Ctrl+H` | Home |
| `Ctrl+B` | Show or hide the navigation pane |
| `F6` / `Shift+F6` | Move between the navigation pane, the page and the console |
| `Ctrl+,` | Settings |
| `Ctrl+L` | Log viewer |
| `F5` | Check for updates |
| `Ctrl+Q` | Exit |
| `↑` / `↓` | Move the selection (lists and palette); `Tab` then reaches the buttons of the selected row |
| `Enter` | Open the selected command: in the catalog, go to its **Run** button; in History, open it in the catalog; in the palette, open it |
| `Esc` | Close a dialog or cancel |
Shortcuts are paused while a dialog is open, and `AltGr` combinations never trigger them, so
typing characters like `@` on international keyboards is safe. `Ctrl+Q` does nothing while you are
typing in a text box (other than a search box), so a slip can't close the app mid-edit. The list is
also under **More → Keyboard shortcuts**.
## Accessibility
- **Keyboard:** everything works without a mouse. After `Ctrl+H`, `Ctrl+,`, `Ctrl+L` or choosing a
page in the navigation pane, the keyboard moves into that page; `F6` jumps between the pane, the
page and the console. The console and the Log viewer can be read line by line with the arrow
keys.
- **Screen readers:** Narrator (and other screen readers) hear when a command starts, needs
administrator permission, finishes (with its result and whether Windows must restart), how many
commands a search found, and each notification.
- **Seeing the screen:** the app follows Windows' contrast themes, its light/dark setting and its
**Text size** setting (Settings › Accessibility › Text size), on top of the app's own font size.
Risk levels are always shown with words or icons, never by color alone.
What works, what doesn't yet, and how to report a barrier:
[ACCESSIBILITY.md](ACCESSIBILITY.md).
## Updates
The app checks `releases.poli0981.dev` for new versions on startup (unless you turned that off)
and when you press `F5`. Version 2.2.0 and older checked GitHub, which is gone: install the new
version once by hand (see [UPDATES.md](UPDATES.md)).
- When an update is available, choose **Download & restart**.
- Closing the dialog cancels the download.
- The app never restarts while a command is running.
See [UPDATES.md](UPDATES.md) for details.
## Your data and uninstalling
Everything stays on your PC:
- Settings, history, recipes, your commands and profiles are in `%AppData%\CommandForge`.
- Logs are in `%AppData%\CommandForge\logs`.
- The program itself is in `%LocalAppData%\CommandForge`.
**More → Portable info** shows the exact folders. Nothing is sent anywhere except the update check
— see [PRIVACY.md](PRIVACY.md).
To uninstall, go to **Settings → Apps → Installed apps** in Windows (**Apps & features** on
Windows 10), find **CommandForge** and choose **Uninstall**. To also remove your settings and history, delete `%AppData%\CommandForge`
afterwards.
## Troubleshooting
- **SmartScreen or antivirus warnings**: releases aren't code-signed yet. See
[verifying your download](README.md#unknown-publisher-and-verifying-your-download).
- **Nothing happens when I open the app**: it runs as a single instance, so a second launch brings
the existing window forward. If it still doesn't appear, check the logs in
`%AppData%\CommandForge\logs`.
- **An admin command didn't run**: it needs the UAC prompt to be approved. Run it again to get a
new prompt. If admin commands keep failing, use **End admin session** and try again.
- **Output looks garbled**: please report it with the command and your Windows display language.
- **Something went wrong**: the error dialog has an **Error code** and **Copy details**.
**Report a bug** (also in the More menu) opens a pre-filled issue on the project's GitLab
mirror. Nothing is sent until you submit it. Export the logs to attach them, but review them first.
+1 -1
View File
@@ -1,6 +1,6 @@
{
"sdk": {
"version": "10.0.301",
"version": "10.0.404",
"rollForward": "latestFeature"
}
}
@@ -6,6 +6,9 @@
<TargetFramework>net10.0-windows</TargetFramework>
<ApplicationManifest>app.manifest</ApplicationManifest>
<RootNamespace>CommandForge.Elevator</RootNamespace>
<!-- The Elevator runs as administrator but inherits the user's environment block: never honour
DOTNET_STARTUP_HOOKS, which would load an arbitrary assembly into the elevated process. -->
<StartupHookSupport>false</StartupHookSupport>
</PropertyGroup>
<ItemGroup>
+13 -18
View File
@@ -2,10 +2,11 @@
//
// Connects to the UI's named pipe and serves ONLY admin commands from its OWN embedded catalog
// (golden rules #1/#2). It never builds a command line from pipe input — it accepts a commandId,
// looks it up, validates requiresAdmin, and runs it.
// looks it up, validates requiresAdmin, and runs it. It writes no files: diagnostics go back to
// the UI over the pipe (a file in the user-writable profile could be redirected by a junction).
using System.IO.Pipes;
using CommandForge.Infrastructure;
using System.Security.Principal;
using CommandForge.Infrastructure.Catalog;
using CommandForge.Infrastructure.Elevation;
using CommandForge.Infrastructure.Execution;
@@ -15,29 +16,23 @@ if (args.Length < 1 || string.IsNullOrWhiteSpace(args[0]))
return 2;
}
var pipeName = args[0];
AppPaths.EnsureCreated();
var logPath = Path.Combine(AppPaths.LogsDirectory, "elevator.log");
void Log(string message) =>
File.AppendAllText(logPath, $"{DateTimeOffset.Now:O} {message}{Environment.NewLine}");
try
{
Log($"Starting; connecting to pipe {pipeName}");
using var client = new NamedPipeClientStream(".", pipeName, PipeDirection.InOut, PipeOptions.Asynchronous);
// Identification level: the (non-elevated) pipe server may learn who we are but cannot act as us.
using var client = new NamedPipeClientStream(".", args[0], PipeDirection.InOut, PipeOptions.Asynchronous, TokenImpersonationLevel.Identification);
await client.ConnectAsync(30_000);
Log("Connected to UI");
var server = new ElevationServer(new JsonCatalogProvider(), new ProcessCommandExecutor(new SystemProcessRunner()));
await server.RunAsync(client, CancellationToken.None);
if (!PeerVerifier.IsExpectedServer(client))
{
return 3; // someone else owns the pipe — serve nothing
}
Log("Pipe closed; exiting");
// Elevated children get a clean environment (see ChildEnvironment for why).
var executor = new ProcessCommandExecutor(new SystemProcessRunner(ChildEnvironment.Apply));
await new ElevationServer(new JsonCatalogProvider(), executor).RunAsync(client, CancellationToken.None);
return 0;
}
catch (Exception ex)
catch (Exception ex) when (ex is IOException or TimeoutException or UnauthorizedAccessException or OperationCanceledException)
{
Log($"Failed: {ex}");
return 1;
}
-46
View File
@@ -1,46 +0,0 @@
# Disclaimer — CommandForge
> **BẢN NHÁP — không phải tư vấn pháp lý.** Rà soát trước khi công bố.
>
> *Cập nhật lần cuối: [ĐIỀN NGÀY]*
---
## ⚠️ Sử dụng với rủi ro của riêng bạn
CommandForge là công cụ **thực thi các lệnh cấp hệ thống** trên Windows. Việc sử dụng có thể dẫn đến:
- Thay đổi cấu hình hệ thống (registry, dịch vụ, tính năng Windows…).
- **Mất dữ liệu** hoặc hệ thống **không ổn định** nếu dùng sai hoặc trong điều kiện không phù hợp.
- Cần khởi động lại máy để hoàn tất một số thao tác.
**Bạn tự chịu hoàn toàn trách nhiệm** với mọi lệnh bạn chọn chạy và mọi hậu quả.
---
## Khuyến nghị an toàn
- **Sao lưu** dữ liệu quan trọng trước khi dùng các lệnh có rủi ro.
- **Tạo System Restore Point** trước các thao tác mức `Caution`/`Dangerous` (ứng dụng có hỗ trợ).
- Đọc kỹ **mô tả & phần xem trước lệnh** trước khi chạy.
- Không chạy lệnh bạn không hiểu rõ.
---
## Không bảo hành
Phần mềm được cung cấp **"NGUYÊN TRẠNG" (AS IS)**, không kèm bảo hành dưới bất kỳ hình thức nào. Tác giả và người đóng góp **không chịu trách nhiệm** cho bất kỳ thiệt hại nào phát sinh từ việc sử dụng phần mềm. Xem chi tiết ở `EULA.md` (mục 3, 4) và `LICENSE` (GPLv3 mục 15, 16).
---
## Không liên kết & nhãn hiệu
- CommandForge là dự án độc lập, **không** liên kết, tài trợ, hay được xác nhận bởi **Microsoft Corporation** hay bất kỳ bên nào.
- "Windows", "Microsoft", "Hyper-V", và các tên liên quan là **nhãn hiệu của Microsoft Corporation**. Các nhãn hiệu khác thuộc về chủ sở hữu tương ứng. Việc nhắc tới chỉ nhằm mục đích mô tả/tương thích.
- Các lệnh được gọi (DISM, SFC, winget, powercfg, netsh…) là **công cụ sẵn có của Windows**; CommandForge chỉ cung cấp giao diện thuận tiện để gọi chúng.
---
## Tính chính xác của thông tin
Mô tả lệnh và tài liệu được cung cấp với thiện chí nhưng **có thể không đầy đủ hoặc không cập nhật** cho mọi phiên bản Windows. Hành vi của lệnh có thể khác nhau giữa Windows 10 và 11 và theo bản cập nhật của hệ điều hành.
-57
View File
@@ -1,57 +0,0 @@
# End User License Agreement (EULA) — CommandForge
> **BẢN NHÁP — không phải tư vấn pháp lý.** Rà soát trước khi công bố.
>
> ⚠️ **Quan trọng:** CommandForge được cấp phép theo **GNU GPL v3** (xem `LICENSE`). **GPLv3 là giấy phép điều chỉnh quyền của bạn đối với phần mềm.** Tài liệu "EULA" này **không** hạn chế bất kỳ quyền nào mà GPLv3 trao cho bạn; nó chỉ là **xác nhận rủi ro và miễn trừ trách nhiệm khi sử dụng**. Nếu có mâu thuẫn, **GPLv3 ưu tiên**.
>
> *Cập nhật lần cuối: [ĐIỀN NGÀY] · Phiên bản: 1.0*
---
## 1. Giấy phép
Phần mềm này là mã nguồn mở theo **GNU General Public License v3.0**. Bạn được quyền sử dụng, sao chép, sửa đổi và phân phối theo các điều khoản của GPLv3. Toàn văn: `LICENSE` (hoặc https://www.gnu.org/licenses/gpl-3.0.html).
Tài liệu này **không thay thế** GPLv3 và **không thêm ràng buộc** trái với GPLv3.
---
## 2. Bản chất phần mềm & chấp nhận rủi ro
Bạn hiểu và đồng ý rằng:
1. CommandForge **thực thi các lệnh cấp hệ thống** (ví dụ DISM, SFC, winget, thay đổi registry, reset mạng…) trên máy của bạn.
2. Các thao tác này **có thể gây thay đổi cấu hình hệ thống, mất dữ liệu, hoặc khiến hệ thống không ổn định** nếu dùng sai hoặc trong điều kiện không phù hợp.
3. Bạn **tự chịu trách nhiệm** với mọi lệnh bạn chọn chạy và mọi hậu quả phát sinh.
4. Bạn nên **sao lưu dữ liệu quan trọng** và cân nhắc **tạo điểm khôi phục (Restore Point)** trước khi chạy lệnh có rủi ro.
---
## 3. Miễn trừ bảo hành
Phần mềm được cung cấp **"NGUYÊN TRẠNG" (AS IS), KHÔNG KÈM BẢO HÀNH** dưới bất kỳ hình thức nào, rõ ràng hay ngụ ý, bao gồm nhưng không giới hạn ở khả năng thương mại, sự phù hợp cho mục đích cụ thể, và không vi phạm. (Phù hợp với **GPLv3 mục 15**.)
---
## 4. Giới hạn trách nhiệm
Trong phạm vi pháp luật cho phép, tác giả/người đóng góp **không chịu trách nhiệm** cho bất kỳ thiệt hại nào (mất dữ liệu, gián đoạn, hư hỏng hệ thống, thiệt hại trực tiếp/gián tiếp/ngẫu nhiên) phát sinh từ việc sử dụng hoặc không thể sử dụng phần mềm. (Phù hợp với **GPLv3 mục 16**.)
---
## 5. Quyền & cách dùng phù hợp
- Sử dụng phần mềm tuân thủ pháp luật áp dụng tại nơi bạn ở.
- Phần mềm dành cho việc quản trị **máy tính của chính bạn** hoặc máy bạn được phép quản trị.
---
## 6. Không liên kết với bên thứ ba
CommandForge **không** liên kết, tài trợ, hay được xác nhận bởi Microsoft hoặc bất kỳ chủ sở hữu thương hiệu nào được nhắc tới. Mọi nhãn hiệu thuộc về chủ sở hữu tương ứng. Xem `Disclaimer.md`.
---
## 7. Chấp nhận
Bằng việc cài đặt và sử dụng phần mềm, bạn xác nhận đã đọc, hiểu và đồng ý với tài liệu này cùng các điều khoản của GPLv3.
-56
View File
@@ -1,56 +0,0 @@
# LICENSE — CommandForge
> Đây là **chỉ dẫn** về giấy phép. Toàn văn GPLv3 nên đặt trong file `LICENSE` (hoặc `COPYING`) ở **gốc repo** — lấy bản chuẩn tại: https://www.gnu.org/licenses/gpl-3.0.txt (đừng tự gõ tay).
---
## Giấy phép dự án
**CommandForge** được cấp phép theo **GNU General Public License v3.0 (GPLv3)**.
- Bạn được tự do **sử dụng, nghiên cứu, sửa đổi và phân phối** phần mềm theo các điều khoản GPLv3.
- Mọi bản phân phối (gồm bản đã sửa) phải **kèm mã nguồn tương ứng** và **giữ nguyên giấy phép GPLv3**.
- Phần mềm cung cấp **không kèm bảo hành** (GPLv3 mục 15, 16).
---
## Cách áp dụng (header gợi ý cho file mã nguồn)
```
CommandForge — giao diện trực quan chạy lệnh hệ thống Windows.
Copyright (C) [NĂM] [TÊN/HANDLE]
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
```
---
## Giấy phép bên thứ ba (tương thích GPLv3)
| Thành phần | Giấy phép |
|---|---|
| .NET 10 runtime, CommunityToolkit.Mvvm, MaterialDesignThemes/Colors, CsWin32, Velopack, System.Text.Json, Microsoft.Extensions.* | MIT |
| Serilog (+ sinks) | Apache-2.0 |
| Cascadia Code/Mono (font) | SIL OFL 1.1 |
| (tùy chọn) Inter / JetBrains Mono | SIL OFL 1.1 |
> MIT, Apache-2.0 và OFL đều **tương thích** với GPLv3. Khi thêm phụ thuộc mới, kiểm tra tương thích trước. Chi tiết phiên bản: `docs/tech.md`.
---
## Ghi nhận
- Font **Cascadia** © Microsoft (OFL).
- Biểu tượng **Material Design Icons** (MIT/OFL).
- Các thư viện mã nguồn mở liệt kê ở trên — cảm ơn cộng đồng.
-61
View File
@@ -1,61 +0,0 @@
# Privacy Policy — CommandForge
> **BẢN NHÁP.** Đây là bản nháp tham khảo, **không phải tư vấn pháp lý**. Hãy rà soát và (nếu cần) nhờ luật sư trước khi công bố. Khi publish, đặt bản công khai trong repo và cập nhật ngày tháng.
>
> *Cập nhật lần cuối: [ĐIỀN NGÀY] · Phiên bản: 1.0*
---
## 1. Tóm tắt (ngắn gọn)
**CommandForge không thu thập, không lưu trữ trên máy chủ, và không gửi đi bất kỳ dữ liệu cá nhân nào của bạn.** Ứng dụng hoạt động hoàn toàn cục bộ trên máy của bạn. Kết nối mạng **duy nhất** là tới GitHub để kiểm tra cập nhật phần mềm.
---
## 2. Dữ liệu được xử lý cục bộ (KHÔNG rời khỏi máy bạn)
| Loại | Nơi lưu | Mục đích |
|---|---|---|
| Cấu hình (theme, ngôn ngữ, favorites, trạng thái chấp nhận điều khoản) | `%AppData%\CommandForge\config.json` | Ghi nhớ tùy chọn của bạn |
| Nhật ký (log) hoạt động ứng dụng | `%AppData%\CommandForge\logs\` | Gỡ lỗi cục bộ |
| Báo cáo do bạn tạo (pin, năng lượng…) | Thư mục bạn chọn | Theo yêu cầu của bạn |
Các dữ liệu này **chỉ nằm trên máy bạn** và **không** được gửi cho chúng tôi hay bên thứ ba.
---
## 3. Kết nối mạng
- **Kiểm tra cập nhật:** Ứng dụng gọi **GitHub** (api/releases) để xem có phiên bản mới và tải bản cập nhật. Quá trình này tuân theo [Chính sách quyền riêng tư của GitHub](https://docs.github.com/site-policy). Chúng tôi không nhận được dữ liệu định danh từ việc này.
- Ngoài ra, ứng dụng **không** thực hiện kết nối mạng nào khác.
---
## 4. Không có telemetry / phân tích
Ứng dụng **không** tích hợp bất kỳ công cụ telemetry, analytics, quảng cáo, hay theo dõi hành vi nào.
---
## 5. Lệnh hệ thống bạn chạy
Khi bạn chạy một lệnh, kết quả (output) được hiển thị trên giao diện và có thể ghi vào log **cục bộ** để gỡ lỗi. Output này **không** được gửi đi đâu. Khi bạn chủ động xuất/chia sẻ log để báo lỗi, hãy tự rà soát nội dung trước khi gửi.
---
## 6. Trẻ em
Ứng dụng không hướng tới trẻ em và không cố ý thu thập dữ liệu của trẻ em (vì không thu thập dữ liệu của ai).
---
## 7. Thay đổi chính sách
Chính sách có thể được cập nhật. Phiên bản mới sẽ kèm ngày cập nhật. Nếu thay đổi đáng kể, ứng dụng có thể yêu cầu bạn xem lại khi khởi động.
---
## 8. Liên hệ
- Repo: `https://github.com/[user]/[repo]`
- Vấn đề/câu hỏi: mở issue, hoặc [ĐIỀN KÊNH LIÊN HỆ].
+102
View File
@@ -0,0 +1,102 @@
# Qodana's settings for .gitea/workflows/qodana.yml (the ops repo's reusable-qodana.yml, Qodana CLI).
#
# The linter is Qodana for .NET (`qodana-dotnet`: Rider's engine) in NATIVE mode, on the job's own
# Windows runner with the .NET SDK that global.json names: the WPF projects (net10.0-windows) load
# only on Windows. It needs the Ultimate licence of the Qodana Cloud project; the token is the
# QODANA_TOKEN repository secret.
#
# Everything a run needs is here and nothing is a workflow argument, so `qodana scan` in the
# repository root of a developer's PC (with QODANA_TOKEN set) reads the same settings. The linter's
# version is the CLI's: the ops workflow pins the CLI (SHA-256 verified), the CLI its linter.
version: "1.0"
linter: qodana-dotnet
withinDocker: false
# WHERE AN INSPECTION IS SWITCHED OFF: one of ReSharper's (C#, XAML, .resx) in .editorconfig
# (`resharper_*_highlighting`), where Rider and ReSharper read it too. Here only what has no key
# there: a whole severity, and the IntelliJ platform's own inspections (Markdown, XML). Each one with
# its reason above it.
profile:
base:
name: qodana.recommended
groups:
# A HINT is what the editor offers without underlining anything (ReSharper's lowest level; this
# linter files it as TYPO, Qodana as Low): "invert if", "convert to LINQ", a trailing comma, and
# every Roslyn analyzer message below the level this build makes an error. They are suggestions,
# not problems, and the build already fails on every warning.
- groupId: Hints
groups:
- "severity:TYPO"
inspections:
- group: Hints
enabled: false
# Windows application manifests: the linter has no schema for urn:schemas-microsoft-com:asm.v1
# and reports every element of the file as undeclared.
- inspection: XmlHighlighting
ignore:
- "src/CommandForge.Wpf/app.manifest"
- "helper/CommandForge.Elevator/app.manifest"
dotnet:
solution: CommandForge.slnx
configuration: Release
# What is not CommandForge's code, or not in the repository: build, package and test output, local
# tool caches, and the git-ignored local folders a developer's PC has (internal notes, IDE state).
exclude:
- name: All
paths:
- Releases
- publish
- TestResults
- .nuget
- docs
- .claude
- .idea
- .vs
# JETBRAINS' SECURITY RULES (the OpenGrep plugin) stay on, and the files their results were READ in
# are listed here - so a new file that starts a process is reported. "A process started with
# something that is not a literal" fired 11 times on the first run (2026-11-16): starting processes
# is what CommandForge is for. What each file starts, and where its path and arguments come from,
# is in tests/CommandForge.Tests/ProcessStartSitesTests.cs, which also fails on a new file. The
# name is the plugin's one inspection, not a rule's: a rule's own id is honoured nowhere, so a
# listed file is left out of all of the plugin's rules - the price.
- name: OpenGrepInspection
paths:
- src/CommandForge.Infrastructure/Execution/SystemProcessRunner.cs
- src/CommandForge.Infrastructure/Elevation/BrokerElevationService.cs
- src/CommandForge.Wpf/Services/ShellService.cs
# The tests start what they test (a read-only PowerShell, the echo of the executor test).
- tests
# THE LINTER'S OWN FAULT, not the file's: resolving PInvoke.CreateJobObject(null, null) - CsWin32's
# null-to-PCWSTR conversion - the engine loses the constructor and reports its locals, its field,
# the class and the file's usings as unused. The compiler builds the file with warnings as errors
# (IDE0005 fails a redundant using). The same engine fault is known from PInvoke.EnumDisplaySettings
# (null, ...). To be removed when a linter build reads the file.
- name: RedundantUsingDirective
paths:
- src/CommandForge.Infrastructure/Execution/ProcessJob.cs
- name: UnusedVariable.Compiler
paths:
- src/CommandForge.Infrastructure/Execution/ProcessJob.cs
- name: NotAccessedField.Compiler
paths:
- src/CommandForge.Infrastructure/Execution/ProcessJob.cs
- name: UnusedField.Compiler
paths:
- src/CommandForge.Infrastructure/Execution/ProcessJob.cs
- name: ClassCannotBeInstantiated
paths:
- src/CommandForge.Infrastructure/Execution/ProcessJob.cs
# The cancellation callback's token source: the registration that captures it is declared after
# it, so it is disposed first, and disposing a registration waits for a callback that is running -
# the source is never used after its disposal.
- name: AccessToDisposedClosure
paths:
- src/CommandForge.Infrastructure/Elevation/BrokerElevationService.cs
# The gate: no problem at all. What the linter reports is settled where it is found — fixed, or its
# inspection switched off with the reason beside it — so a count above zero is something new.
failureConditions:
severityThresholds:
any: 0
+23
View File
@@ -0,0 +1,23 @@
{
"$schema": "https://docs.renovatebot.com/renovate-schema.json",
"extends": ["local>poli0981/renovate-config"],
"packageRules": [
{
"description": "Maintenance mode: a major lands only in a planned release with its migration. It waits on the Dependency Dashboard until it is ticked there; minor and patch updates come in the preset's grouped pull request.",
"matchUpdateTypes": ["major"],
"dependencyDashboardApproval": true
},
{
"description": "The app stays on the .NET 10 LTS line: Microsoft.Extensions.* majors follow .NET majors, and moving to a new .NET major (the SDK in global.json included) is a migration done by hand, never a bot bump.",
"matchPackageNames": ["Microsoft.Extensions.**", "dotnet-sdk"],
"matchUpdateTypes": ["major"],
"enabled": false
},
{
"description": "The Velopack library (CommandForge.Infrastructure, CommandForge.Wpf) and the vpk CLI (.config/dotnet-tools.json) must be the same version: one pull request of their own.",
"matchPackageNames": ["Velopack", "vpk"],
"groupName": "Velopack",
"groupSlug": "velopack"
}
]
}
+54 -20
View File
@@ -1,19 +1,28 @@
#requires -Version 7
<#
.SYNOPSIS
Publishes CommandForge self-contained and packages it with Velopack (vpk) for GitHub Releases.
Publishes CommandForge self-contained and packages it with Velopack (vpk).
.DESCRIPTION
Phase 4 release helper (no CI — that is Phase 6). Produces, under Releases/:
CommandForge-win-Setup.exe, RELEASES, *-full.nupkg, *-delta.nupkg
Update is per-user (no UAC). The Elevator is copied into the publish dir by the
CopyElevatorOnPublish MSBuild target, so vpk packages it automatically.
Produces, under Releases/:
CommandForge-win-Setup.exe, CommandForge-win-Portable.zip, RELEASES, releases.win.json,
*-full.nupkg, *-delta.nupkg
scripts/release-assets.ps1 adds the SBOM, SHA256SUMS and the release notes; release.yml uploads
the lot to Cloudflare R2 (https://releases.poli0981.dev/commandforge, `vpk upload s3`).
Update is per-user (no UAC). The Elevator is published into the same folder by the
PublishElevatorOnPublish MSBuild target, so vpk packages it automatically.
vpk is pinned as a local .NET tool (.config/dotnet-tools.json) and must match the Velopack
library version referenced by CommandForge.Infrastructure.csproj and CommandForge.Wpf.csproj.
.PARAMETER Version
SemVer package version, e.g. 0.3.0 (no leading 'v'). Should match the git tag vX.Y.Z.
SemVer package version, e.g. 2.0.0 (no leading 'v'). Should match the git tag vX.Y.Z.
.PARAMETER SkipPack
Publish only (no vpk pack) — used by the CI packaging smoke test when vpk is not wanted.
.EXAMPLE
./scripts/pack.ps1 -Version 0.3.0
./scripts/pack.ps1 -Version 2.0.0
#>
[CmdletBinding()]
param(
@@ -22,7 +31,9 @@ param(
[string] $Runtime = 'win-x64',
[string] $Configuration = 'Release'
[string] $Configuration = 'Release',
[switch] $SkipPack
)
$ErrorActionPreference = 'Stop'
@@ -33,25 +44,48 @@ $wpfProject = Join-Path $repoRoot 'src/CommandForge.Wpf'
Write-Host "Publishing CommandForge $Version ($Runtime, $Configuration)..." -ForegroundColor Cyan
# Stamp the assembly version so the in-app "App version" (Settings -> About, Report Bug) matches
# the released package version; otherwise it stays at the 1.0.0 default regardless of the tag.
# the released package version. ReadyToRun precompiles the app's own assemblies for faster startup
# (the self-contained framework assemblies are already precompiled).
dotnet publish $wpfProject `
-c $Configuration -r $Runtime --self-contained true `
-p:PublishSingleFile=false `
-p:PublishReadyToRun=true `
-p:Version=$Version -p:FileVersion=$Version -p:InformationalVersion=$Version `
-o $publishDir
if ($LASTEXITCODE -ne 0) { throw "dotnet publish failed with exit code $LASTEXITCODE" }
# vpk is the Velopack CLI: dotnet tool install -g vpk
if (-not (Get-Command vpk -ErrorAction SilentlyContinue)) {
throw "vpk not found. Install it with: dotnet tool install -g vpk"
# The elevated helper must ship next to the app (BrokerElevationService spawns it from there).
foreach ($file in 'CommandForge.Wpf.exe', 'CommandForge.Elevator.exe', 'CommandForge.Elevator.dll') {
if (-not (Test-Path (Join-Path $publishDir $file))) {
throw "Publish output is missing $file"
}
}
Write-Host "Packing with Velopack..." -ForegroundColor Cyan
vpk pack `
--packId CommandForge `
--packTitle CommandForge `
--packAuthors poli0981 `
--packVersion $Version `
--packDir $publishDir `
--mainExe CommandForge.Wpf.exe
if ($SkipPack) {
Write-Host "Publish OK (pack skipped). Output: $publishDir" -ForegroundColor Green
return
}
Push-Location $repoRoot
try {
dotnet tool restore
if ($LASTEXITCODE -ne 0) { throw "dotnet tool restore failed with exit code $LASTEXITCODE" }
Write-Host "Packing with Velopack..." -ForegroundColor Cyan
# --runtime selects native x64 Update.exe/Setup.exe helpers (vpk otherwise defaults to x86);
# the update channel stays the default "win", so existing installs keep receiving updates.
dotnet vpk pack `
--runtime $Runtime `
--packId CommandForge `
--packTitle CommandForge `
--packAuthors poli0981 `
--packVersion $Version `
--packDir $publishDir `
--mainExe CommandForge.Wpf.exe
if ($LASTEXITCODE -ne 0) { throw "vpk pack failed with exit code $LASTEXITCODE" }
}
finally {
Pop-Location
}
Write-Host "Done. Artifacts are in $(Join-Path $repoRoot 'Releases')." -ForegroundColor Green
+129
View File
@@ -0,0 +1,129 @@
#requires -Version 7
<#
.SYNOPSIS
Writes the release's SBOM, SHA256SUMS and release notes next to the Velopack output.
.DESCRIPTION
Run after scripts/pack.ps1 (release.yml does; it also runs locally, as a dry run). Produces:
<OutputDir>/versioned/<Version>/sbom.cdx.json CycloneDX SBOM of the solution (test projects
left out; build-only packages listed with
scope "excluded")
<OutputDir>/versioned/<Version>/SHA256SUMS sha256sum format, one line per file below
<OutputDir>/release-notes.md CHANGELOG.md section + download links
release.yml uploads `versioned/` to https://releases.poli0981.dev/commandforge/<Version>/ with the
ops repo's publish-r2.yml, and uses release-notes.md as the Gitea release's body.
SHA256SUMS covers what this version ships: the installer and the portable zip (stable names
at the folder root, replaced by the next release), this version's full and delta packages, and
the SBOM. Not the feed files (releases.win.json, assets.win.json, RELEASES): `vpk upload`
rewrites them on every release, so a checksum of them is stale at the next one.
.PARAMETER Version
SemVer version without the leading 'v', e.g. 2.3.0.
.PARAMETER VirusTotalAnalysis
Optional: the `analysis` output of crazy-max/ghaction-virustotal ("path=url,path=url"). Each
file gets a link to its permanent VirusTotal report in the notes.
.EXAMPLE
./scripts/pack.ps1 -Version 2.3.0; ./scripts/release-assets.ps1 -Version 2.3.0
#>
[CmdletBinding()]
param(
[Parameter(Mandatory = $true)]
[string] $Version,
[string] $ReleasesDir = 'Releases',
[string] $OutputDir = 'r2-release',
[string] $BaseUrl = 'https://releases.poli0981.dev/commandforge',
[string] $VirusTotalAnalysis = ''
)
$ErrorActionPreference = 'Stop'
if ($Version -notmatch '^\d+\.\d+\.\d+$') { throw "Version '$Version' is not X.Y.Z" }
$repoRoot = Split-Path -Parent $PSScriptRoot
Push-Location $repoRoot
try {
$releases = (Resolve-Path -LiteralPath $ReleasesDir).Path
$versioned = Join-Path $OutputDir "versioned/$Version"
New-Item -ItemType Directory -Force -Path $versioned | Out-Null
# --- What this version ships -------------------------------------------------------------
$required = @('CommandForge-win-Setup.exe', 'CommandForge-win-Portable.zip', "CommandForge-$Version-full.nupkg")
foreach ($name in $required) {
if (-not (Test-Path -LiteralPath (Join-Path $releases $name) -PathType Leaf)) {
throw "$ReleasesDir is missing $name (run scripts/pack.ps1 -Version $Version first)"
}
}
# The delta exists only when the previous release was downloaded before packing.
$delta = "CommandForge-$Version-delta.nupkg"
$shipped = @($required) + @(if (Test-Path -LiteralPath (Join-Path $releases $delta)) { $delta })
# --- SBOM (CycloneDX) ----------------------------------------------------------------------
Write-Host "Writing the CycloneDX SBOM..." -ForegroundColor Cyan
dotnet tool run dotnet-CycloneDX CommandForge.slnx `
--exclude-test-projects `
--configuration Release `
--output $versioned `
--filename sbom.cdx.json `
--output-format Json `
--set-name CommandForge `
--set-version $Version
if ($LASTEXITCODE -ne 0) { throw "CycloneDX failed with exit code $LASTEXITCODE" }
$sbom = Join-Path $versioned 'sbom.cdx.json'
# --- SHA256SUMS ----------------------------------------------------------------------------
$files = @($shipped | ForEach-Object { Get-Item -LiteralPath (Join-Path $releases $_) }) + (Get-Item -LiteralPath $sbom)
$lines = $files |
Sort-Object Name |
ForEach-Object { '{0} {1}' -f (Get-FileHash -Algorithm SHA256 -LiteralPath $_.FullName).Hash.ToLowerInvariant(), $_.Name }
# LF line endings, as sha256sum writes and `sha256sum -c` expects.
[IO.File]::WriteAllText((Join-Path $versioned 'SHA256SUMS'), (($lines -join "`n") + "`n"), [Text.Encoding]::ASCII)
$lines | ForEach-Object { Write-Host $_ }
# --- Release notes -------------------------------------------------------------------------
$changelog = (Get-Content CHANGELOG.md -Raw) -replace "`r`n", "`n"
$pattern = "(?ms)^## \[$([regex]::Escape($Version))\][^\n]*\n(.*?)(?=^## \[|^\[[^\]]+\]: |\z)"
$section = [regex]::Match($changelog, $pattern, 'None', [TimeSpan]::FromSeconds(5))
if (-not ($section.Success -and $section.Groups[1].Value.Trim())) {
throw "CHANGELOG.md has no section for $Version"
}
$vbase = "$BaseUrl/$Version"
$notes = [Collections.Generic.List[string]]::new()
$notes.Add($section.Groups[1].Value.Trim())
$notes.AddRange([string[]]@(
'', '## Download (Windows 10/11, x64)', '',
"- Installer: [CommandForge-win-Setup.exe]($BaseUrl/CommandForge-win-Setup.exe)",
"- Portable: [CommandForge-win-Portable.zip]($BaseUrl/CommandForge-win-Portable.zip)",
"- [SHA256SUMS]($vbase/SHA256SUMS) · [SBOM (CycloneDX)]($vbase/sbom.cdx.json)",
'',
'The installer and the portable zip always hold the newest release; the checksums below are this one''s.',
'Installed copies update from the app (More (⋯) → Check for updates). Versions 2.2.0 and older',
'checked GitHub, which is gone: install this version once by hand, over the old one.',
'', '```', ($lines -join "`n"), '```'))
if ($VirusTotalAnalysis) {
$notes.AddRange([string[]]@('', '### VirusTotal', ''))
foreach ($pair in $VirusTotalAnalysis -split ',') {
$file = ($pair -split '=', 2)[0]
if (-not $file) { continue }
$hash = (Get-FileHash -Algorithm SHA256 -LiteralPath $file).Hash.ToLowerInvariant()
$notes.Add(('- [{0}](https://www.virustotal.com/gui/file/{1})' -f (Split-Path $file -Leaf), $hash))
}
}
$notesPath = Join-Path $OutputDir 'release-notes.md'
[IO.File]::WriteAllText($notesPath, (($notes -join "`n") + "`n"), [Text.UTF8Encoding]::new($false))
Write-Host "Release notes: $notesPath" -ForegroundColor Green
}
finally {
Pop-Location
}
@@ -0,0 +1,51 @@
using System.Text.RegularExpressions;
namespace CommandForge.Application;
/// <summary>
/// Placeholders a catalog <c>argsTemplate</c> may use for machine-specific paths, e.g.
/// <c>chkdsk {SystemDrive}</c>. The executor fills them from trusted OS sources — never from
/// environment variables, which a standard user can redefine even for elevated processes.
/// </summary>
public static partial class ArgumentTokens
{
/// <summary>The Windows drive, e.g. <c>C:</c>.</summary>
public const string SystemDrive = "{SystemDrive}";
/// <summary>The Windows directory, e.g. <c>C:\Windows</c>.</summary>
public const string SystemRoot = "{SystemRoot}";
/// <summary>The current user's profile folder, e.g. <c>C:\Users\name</c>.</summary>
public const string UserProfile = "{UserProfile}";
/// <summary>Every supported token.</summary>
public static IReadOnlyList<string> All { get; } = [SystemDrive, SystemRoot, UserProfile];
/// <summary>Replaces each token present in <paramref name="values"/>; anything else is left as-is.</summary>
public static string Expand(string template, IReadOnlyDictionary<string, string> values)
{
ArgumentNullException.ThrowIfNull(template);
ArgumentNullException.ThrowIfNull(values);
foreach (var (token, value) in values)
{
template = template.Replace(token, value, StringComparison.Ordinal);
}
return template;
}
/// <summary>Token-like sequences (<c>{Word}</c>) in <paramref name="template"/> that are not supported tokens.</summary>
public static IReadOnlyList<string> FindUnknown(string template)
{
ArgumentNullException.ThrowIfNull(template);
return TokenPattern().Matches(template)
.Select(m => m.Value)
.Where(token => !All.Contains(token, StringComparer.Ordinal))
.Distinct(StringComparer.Ordinal)
.ToList();
}
[GeneratedRegex(@"\{[A-Z][A-Za-z]+\}", RegexOptions.CultureInvariant, matchTimeoutMilliseconds: 1000)]
private static partial Regex TokenPattern();
}
@@ -4,16 +4,21 @@ namespace CommandForge.Application;
/// <summary>
/// Builds the exact command line shown to the user before running (transparency —
/// see docs/Security.md §1). Display only; execution uses an argument array, not this string.
/// see docs/Security.md §1). The executor passes the same argument string to the process.
/// </summary>
public static class CommandPreview
{
/// <summary>Returns <c>executable args</c>, or just the executable when there are no args.</summary>
/// <summary>Returns <c>executable args</c> with path tokens left as placeholders.</summary>
public static string Build(CommandDefinition command)
=> Build(command, new Dictionary<string, string>());
/// <summary>Returns <c>executable args</c> with <see cref="ArgumentTokens"/> replaced by <paramref name="tokens"/>.</summary>
public static string Build(CommandDefinition command, IReadOnlyDictionary<string, string> tokens)
{
ArgumentNullException.ThrowIfNull(command);
ArgumentNullException.ThrowIfNull(tokens);
var args = command.ArgsTemplate.Trim();
var args = ArgumentTokens.Expand(command.ArgsTemplate, tokens).Trim();
return args.Length == 0 ? command.Executable : $"{command.Executable} {args}";
}
}
@@ -9,12 +9,21 @@ namespace CommandForge.Application.Ports;
/// </summary>
public interface IElevationService
{
/// <summary>Whether elevation is currently available (broker reachable).</summary>
public bool IsElevationAvailable { get; }
/// <summary>Whether an elevated session (a connected Elevator) is currently open.</summary>
public bool IsSessionActive { get; }
/// <summary>Raised, on any thread, when a session starts or ends; <see cref="IsSessionActive"/> has the new state.</summary>
public event EventHandler? SessionChanged;
/// <summary>Runs <paramref name="command"/> elevated via the broker, streaming output lines.</summary>
public Task<ExecutionResult> RunElevatedAsync(
CommandDefinition command,
ChannelWriter<OutputLine> output,
CancellationToken cancellationToken = default);
/// <summary>
/// Ends the elevated session and waits (briefly) for the Elevator to exit — e.g. before an
/// update replaces the files it is running from. The next admin command starts a new session.
/// </summary>
public Task EndSessionAsync(CancellationToken cancellationToken = default);
}
@@ -1,10 +0,0 @@
namespace CommandForge.Application.Ports;
/// <summary>
/// Creates a System Restore Point before risky operations.
/// </summary>
public interface IRestorePointService
{
/// <summary>Creates a restore point with the given description. Returns whether it succeeded.</summary>
public Task<bool> CreateRestorePointAsync(string description, CancellationToken cancellationToken = default);
}
@@ -11,13 +11,13 @@ public interface ISettingsService
/// <summary>The terms version the user last accepted, or <see langword="null"/> if none.</summary>
public string? AcceptedTermsVersion { get; set; }
/// <summary>Whether to check GitHub Releases for updates on startup (default <see langword="true"/>). Local-only.</summary>
/// <summary>Whether to check the update feed for updates on startup (default <see langword="true"/>). Local-only.</summary>
public bool AutoCheckForUpdates { get; set; }
/// <summary>The UI color theme (default <see cref="AppTheme.System"/>).</summary>
public AppTheme Theme { get; set; }
/// <summary>UI language: <c>""</c> = follow OS, otherwise a culture code such as <c>"en"</c> or <c>"vi"</c>.</summary>
/// <summary>UI language: <c>""</c> = follow OS, otherwise a culture code such as <c>"en"</c>, <c>"vi"</c>, <c>"ja"</c>, <c>"zh-Hans"</c> or <c>"es"</c>.</summary>
public string Language { get; set; }
/// <summary>The overall UI font size (default <see cref="FontScale.Medium"/>).</summary>
@@ -39,7 +39,7 @@ public interface ISettingsService
/// <summary>Whether the console auto-scrolls to the latest output (default <see langword="true"/>).</summary>
public bool AutoScrollConsole { get; set; }
/// <summary>Whether to warn before closing/cancelling while a command is running (default <see langword="true"/>).</summary>
/// <summary>Whether to ask before closing the app while a command is running (default <see langword="true"/>).</summary>
public bool WarnOnCancel { get; set; }
/// <summary>The minimum log level captured by the logging pipeline (default <see cref="LogLevel.Information"/>).</summary>
@@ -51,10 +51,10 @@ public interface ISettingsService
/// <summary>Recently-run command ids, most-recent first (default empty). Capped by the caller.</summary>
public IReadOnlyList<string> RecentCommandIds { get; set; }
/// <summary>Last main-window width in device-independent pixels, or <see langword="null"/> if never saved.</summary>
/// <summary>Last main-window width in DIPs (restored size), or <see langword="null"/> if never saved (default size).</summary>
public double? WindowWidth { get; set; }
/// <summary>Last main-window height in device-independent pixels, or <see langword="null"/> if never saved.</summary>
/// <summary>Last main-window height in DIPs (restored size), or <see langword="null"/> if never saved (default size).</summary>
public double? WindowHeight { get; set; }
/// <summary>Last main-window left position, or <see langword="null"/> if never saved (centre on launch).</summary>
@@ -63,7 +63,7 @@ public interface ISettingsService
/// <summary>Last main-window top position, or <see langword="null"/> if never saved (centre on launch).</summary>
public double? WindowTop { get; set; }
/// <summary>Whether the main window was maximized when last closed (default <see langword="false"/>).</summary>
/// <summary>Whether the main window was maximized when it was last closed.</summary>
public bool WindowMaximized { get; set; }
/// <summary>Persists the current settings to disk.</summary>
@@ -1,21 +1,26 @@
namespace CommandForge.Application.Ports;
/// <summary>
/// Checks GitHub Releases for application updates (via Velopack) and applies them.
/// Per-user install ⇒ no UAC, so it never interacts with the elevation broker.
/// Checks the release feed (<see cref="ProductLinks.UpdateFeed"/>) for application updates (via Velopack) and applies them.
/// Per-user install ⇒ no UAC; applying ends any elevated session first.
/// </summary>
public interface IUpdateService
{
/// <summary>Whether the running app was installed via Velopack (false in dev/unpackaged).</summary>
public bool IsUpdateSupported { get; }
/// <summary>Checks GitHub Releases for a newer version, mapping HTTP failures to <see cref="UpdateError"/>.</summary>
/// <summary>Checks the release feed for a newer version, mapping HTTP failures to <see cref="UpdateError"/>.</summary>
public Task<UpdateCheckResult> CheckForUpdatesAsync(CancellationToken cancellationToken = default);
/// <summary>
/// Downloads (delta if available) and applies the pending update from the last successful check,
/// then restarts. Reports progress 0-100 via <paramref name="progress"/>. Returns an
/// <see cref="UpdateError"/> on failure; on success the process exits and this does not return.
/// Downloads (delta if available) the update found by the last successful check, reporting
/// progress 0-100. Returns <see cref="UpdateError.None"/> once it is ready to apply.
/// </summary>
public Task<UpdateError> DownloadAndApplyAsync(IProgress<int>? progress, CancellationToken cancellationToken = default);
public Task<UpdateError> DownloadAsync(IProgress<int>? progress, CancellationToken cancellationToken = default);
/// <summary>
/// Ends the elevated session (the Elevator runs from the folder being replaced), applies the
/// downloaded update and restarts. On success the process exits and this does not return.
/// </summary>
public Task<UpdateError> ApplyAndRestartAsync(CancellationToken cancellationToken = default);
}
@@ -2,23 +2,24 @@ namespace CommandForge.Application.Ports;
/// <summary>
/// Mapped failure categories for an update check or download (see <c>architectures.md</c> §5).
/// GitHub uses 403 (primary rate limit) and 429 (secondary) — there is no 419.
/// The feed is served by Cloudflare: 403 when its edge refuses a request, 429 when it limits them —
/// there is no 419.
/// </summary>
public enum UpdateError
{
/// <summary>No error.</summary>
None = 0,
/// <summary>No network / DNS failure / request could not reach GitHub.</summary>
/// <summary>No network / DNS failure / request could not reach the update server.</summary>
Offline,
/// <summary>404 — the release feed or repository was not found.</summary>
/// <summary>404 — the release feed was not found.</summary>
NotFound,
/// <summary>403 or 429 — GitHub rate limit reached.</summary>
/// <summary>403 or 429 — the update server refused or rate-limited the request.</summary>
RateLimited,
/// <summary>5xx — GitHub or its CDN returned a server error.</summary>
/// <summary>5xx — the update server or its CDN returned a server error.</summary>
ServerError,
/// <summary>The app is not Velopack-installed (dev/unpackaged); updates do not apply.</summary>
@@ -0,0 +1,8 @@
namespace CommandForge.Application;
/// <summary>Fixed product identity strings that are not localized (brand name).</summary>
public static class ProductInfo
{
/// <summary>The product name, used where localized resources may be unavailable (e.g. startup failures).</summary>
public const string Name = "CommandForge";
}
@@ -0,0 +1,62 @@
namespace CommandForge.Application;
/// <summary>
/// The project's canonical public links, in one place so the update source, About, Settings, the
/// legal pages and the bug-report flow can never drift apart. The source lives on the maintainer's
/// Gitea (read-only for everyone else), issues on its GitLab mirror, releases on Cloudflare R2.
/// </summary>
#pragma warning disable S1075 // These are the product's fixed public URLs, not environment-specific paths.
public static class ProductLinks
{
/// <summary>The canonical repository on Gitea.</summary>
public const string Repository = "https://git.poli0981.dev/poli0981/CommandForge";
/// <summary>A file on the repository's main branch, as Gitea shows it.</summary>
private const string MainBranch = Repository + "/src/branch/main/";
/// <summary>
/// The Velopack update feed (<c>releases.win.json</c> and the packages), served by Cloudflare
/// from R2. The only address the app contacts on its own.
/// </summary>
public const string UpdateFeed = "https://releases.poli0981.dev/commandforge";
/// <summary>Releases page (release notes and download links).</summary>
public const string Releases = Repository + "/releases";
/// <summary>Issues, on the public GitLab mirror (Gitea's registration is closed).</summary>
public const string Issues = "https://gitlab.com/poli0981/CommandForge/-/issues";
/// <summary>New issue on the GitLab mirror, used by "Report a bug".</summary>
public const string NewIssue = Issues + "/new";
/// <summary>The end-user guide in the repository.</summary>
public const string UserGuide = MainBranch + "USAGE.md";
/// <summary>Private security reports, by email only.</summary>
public const string SecurityEmail = "security@poli0981.dev";
/// <summary>Questions about the code, contributions and patches.</summary>
public const string CodeEmail = "code@poli0981.dev";
/// <summary>The accessibility statement: what works, the known limitations, how to report a barrier.</summary>
public const string AccessibilityStatement = MainBranch + "ACCESSIBILITY.md";
/// <summary>Accessibility barriers by email (the alternative to the issue template).</summary>
public const string AccessibilityEmail = "accessibility@poli0981.dev";
/// <summary>The End User License Agreement in the repository.</summary>
public const string Eula = MainBranch + "EULA.md";
/// <summary>The project's LICENSE file (GPLv3) in the repository.</summary>
public const string LicenseFile = MainBranch + "LICENSE";
/// <summary>The disclaimer in the repository.</summary>
public const string Disclaimer = MainBranch + "DISCLAIMER.md";
/// <summary>The privacy policy in the repository.</summary>
public const string Privacy = MainBranch + "PRIVACY.md";
/// <summary>Full text of the GNU GPL v3.</summary>
public const string License = "https://www.gnu.org/licenses/gpl-3.0.html";
}
#pragma warning restore S1075
@@ -39,11 +39,11 @@ public static class RegistrySnapshot
var changes = new List<RegistryChange>();
foreach (var reference in references)
{
before.TryGetValue(reference, out var b);
after.TryGetValue(reference, out var a);
if (!string.Equals(b, a, StringComparison.Ordinal))
before.TryGetValue(reference, out var oldValue);
after.TryGetValue(reference, out var newValue);
if (!string.Equals(oldValue, newValue, StringComparison.Ordinal))
{
changes.Add(new RegistryChange(reference, b, a));
changes.Add(new RegistryChange(reference, oldValue, newValue));
}
}
+81
View File
@@ -0,0 +1,81 @@
using System.Text;
using CommandForge.Domain;
namespace CommandForge.Application;
/// <summary>
/// The confirmation and restore-point rules, in one place so single runs, re-runs from History,
/// reverts and recipes all apply them identically (golden rule #8).
/// </summary>
public static class RunSafety
{
/// <summary>The vetted catalog command that creates a System Restore Point.</summary>
public const string RestorePointCommandId = "system.restorepoint";
/// <summary>
/// Exit code of <see cref="RestorePointCommandId"/> when Windows created nothing because another
/// restore point was made recently (it allows one per 24 hours) — not a failure.
/// </summary>
public const int RestorePointSkippedExitCode = 2;
/// <summary>Dangerous commands always ask; Caution ones ask unless the user turned that off.</summary>
public static bool NeedsConfirmation(CommandDefinition command, bool confirmCaution)
{
ArgumentNullException.ThrowIfNull(command);
return command.DangerLevel == DangerLevel.Dangerous
|| (command.DangerLevel == DangerLevel.Caution && confirmCaution);
}
/// <summary>Dangerous commands require typing the title (or id) — never just a click.</summary>
public static bool NeedsTypedConfirmation(CommandDefinition command)
{
ArgumentNullException.ThrowIfNull(command);
return command.DangerLevel == DangerLevel.Dangerous;
}
/// <summary>
/// Whether a restore point is offered before <paramref name="command"/>: for commands the
/// catalog flags, and for risky admin commands. Never for per-user (non-admin) tweaks — creating
/// a restore point needs administrator rights, so it would add a UAC prompt they don't need.
/// </summary>
public static bool OffersRestorePoint(CommandDefinition command)
{
ArgumentNullException.ThrowIfNull(command);
if (string.Equals(command.Id, RestorePointCommandId, StringComparison.Ordinal))
{
return false;
}
return command.CreatesRestorePoint
|| (command.RequiresAdmin && command.DangerLevel >= DangerLevel.Caution);
}
/// <summary>The initial state of the restore-point checkbox.</summary>
public static bool DefaultCreateRestorePoint(CommandDefinition command, bool autoCreateRestorePoint)
{
ArgumentNullException.ThrowIfNull(command);
return OffersRestorePoint(command) && (command.CreatesRestorePoint || autoCreateRestorePoint);
}
/// <summary>
/// Whether <paramref name="input"/> confirms a Dangerous command: the title as displayed, or the
/// command id. Unicode-normalized (Vietnamese input methods may type decomposed accents) and
/// case-insensitive, so what looks identical always matches.
/// </summary>
public static bool IsTypedConfirmationValid(string? input, string title, string commandId)
{
ArgumentNullException.ThrowIfNull(title);
ArgumentNullException.ThrowIfNull(commandId);
if (string.IsNullOrWhiteSpace(input))
{
return false;
}
var typed = Normalize(input);
return string.Equals(typed, Normalize(title), StringComparison.OrdinalIgnoreCase)
|| string.Equals(typed, commandId.Trim(), StringComparison.OrdinalIgnoreCase);
}
private static string Normalize(string value)
=> value.Trim().Normalize(NormalizationForm.FormC);
}
@@ -4,8 +4,9 @@ namespace CommandForge.Application.Search;
public readonly record struct FuzzyMatchResult(int Score, IReadOnlyList<int> MatchedIndices);
/// <summary>
/// Lightweight case-insensitive subsequence fuzzy matcher. Rewards consecutive matches and
/// matches at word boundaries so the most relevant results rank first. No external dependency.
/// Lightweight accent- and case-insensitive subsequence matcher. Rewards consecutive matches and
/// matches at word boundaries, and tries every starting point so "flush" lights up the word
/// "flush" rather than the first "f" and "l" it meets. No external dependency.
/// </summary>
public static class FuzzyMatcher
{
@@ -14,7 +15,7 @@ public static class FuzzyMatcher
private const int WordBoundaryBonus = 10;
/// <summary>
/// Returns a match for <paramref name="query"/> within <paramref name="text"/>, or
/// Returns the best match for <paramref name="query"/> within <paramref name="text"/>, or
/// <see langword="null"/> if not all query characters appear in order. An empty query
/// matches everything with score 0.
/// </summary>
@@ -33,43 +34,61 @@ public static class FuzzyMatcher
return null;
}
var foldedText = TextFolding.Fold(text);
var foldedQuery = TextFolding.Fold(query);
FuzzyMatchResult? best = null;
for (var start = foldedText.IndexOf(foldedQuery[0]);
start >= 0;
start = foldedText.IndexOf(foldedQuery[0], start + 1))
{
if (MatchFrom(foldedText, foldedQuery, start) is { } candidate
&& (best is null || candidate.Score > best.Value.Score))
{
best = candidate;
}
}
return best;
}
/// <summary>The smallest score a title match of <paramref name="queryLength"/> characters needs to count.</summary>
public static int MinimumUsefulScore(int queryLength)
=> queryLength <= 1 ? BaseScore : queryLength * BaseScore + (queryLength - 1) * 4;
private static FuzzyMatchResult? MatchFrom(string text, string query, int start)
{
var indices = new List<int>(query.Length);
var score = 0;
var textIndex = 0;
var textIndex = start;
var lastMatch = -2;
foreach (var queryChar in query)
foreach (var target in query)
{
var found = false;
for (; textIndex < text.Length; textIndex++)
while (textIndex < text.Length && text[textIndex] != target)
{
if (char.ToLowerInvariant(text[textIndex]) != char.ToLowerInvariant(queryChar))
{
continue;
}
indices.Add(textIndex);
score += BaseScore;
if (textIndex == lastMatch + 1)
{
score += ConsecutiveBonus;
}
if (textIndex == 0 || !char.IsLetterOrDigit(text[textIndex - 1]))
{
score += WordBoundaryBonus;
}
lastMatch = textIndex;
textIndex++;
found = true;
break;
}
if (!found)
if (textIndex >= text.Length)
{
return null;
}
indices.Add(textIndex);
score += BaseScore;
if (textIndex == lastMatch + 1)
{
score += ConsecutiveBonus;
}
if (textIndex == 0 || !char.IsLetterOrDigit(text[textIndex - 1]))
{
score += WordBoundaryBonus;
}
lastMatch = textIndex;
textIndex++;
}
return new FuzzyMatchResult(score, indices);
@@ -2,7 +2,8 @@ namespace CommandForge.Application.Search;
/// <summary>
/// Local natural-language search: maps everyday EN/VI phrases to a catalog search keyword
/// (e.g. "clean disk" / "dọn ổ đĩa" → "cleanup"). 100% LOCAL — no LLM, no network (golden rule #5).
/// (e.g. "clean disk" / "dọn ổ đĩa" → "cleanup"). 100% LOCAL — no LLM, no network (golden rule #7).
/// Phrases match whole words, ignoring case and accents ("pin" is battery, "typing" is not).
/// </summary>
public static class NaturalLanguageSearch
{
@@ -40,10 +41,10 @@ public static class NaturalLanguageSearch
return null;
}
var text = query.Trim().ToLowerInvariant();
var text = TextFolding.Fold(query.Trim());
foreach (var (phrase, keyword) in Map)
{
if (text.Contains(phrase, StringComparison.Ordinal)
if (ContainsWholeWords(text, TextFolding.Fold(phrase))
&& !string.Equals(text, keyword, StringComparison.Ordinal))
{
return keyword;
@@ -52,4 +53,20 @@ public static class NaturalLanguageSearch
return null;
}
private static bool ContainsWholeWords(string text, string phrase)
{
for (var at = text.IndexOf(phrase, StringComparison.Ordinal); at >= 0; at = text.IndexOf(phrase, at + 1, StringComparison.Ordinal))
{
var end = at + phrase.Length;
var startsWord = at == 0 || !char.IsLetterOrDigit(text[at - 1]);
var endsWord = end == text.Length || !char.IsLetterOrDigit(text[end]);
if (startsWord && endsWord)
{
return true;
}
}
return false;
}
}
@@ -4,13 +4,21 @@ namespace CommandForge.Application.Search;
/// <summary>
/// A command paired with its resolved (localized) searchable text. The presentation layer
/// resolves resource keys to text and supplies these, keeping search logic free of i18n.
/// resolves resource keys to text and supplies these, keeping search logic free of i18n. The
/// accent-/case-folded forms are computed once here, not on every keystroke.
/// </summary>
public sealed record SearchableCommand(
CommandDefinition Command,
string Title,
string Description,
IReadOnlyList<string> Tags);
IReadOnlyList<string> Tags)
{
internal string FoldedTitle { get; } = TextFolding.Fold(Title);
internal string FoldedDescription { get; } = TextFolding.Fold(Description);
internal IReadOnlyList<string> FoldedTags { get; } = Tags.Select(TextFolding.Fold).ToList();
}
/// <summary>Optional filters applied before fuzzy ranking.</summary>
public sealed record CommandSearchFilter
@@ -41,7 +49,8 @@ public sealed record CommandSearchFilter
return false;
}
if (RequiresRestart is { } restart && (command.Restart != RestartPolicy.No) != restart)
// "Requires restart" means always; exit-code/regex policies only restart sometimes.
if (RequiresRestart is { } restart && (command.Restart == RestartPolicy.Always) != restart)
{
return false;
}
@@ -59,12 +68,20 @@ public sealed record CommandSearchFilter
public sealed record CommandSearchHit(CommandDefinition Command, int Score, IReadOnlyList<int> TitleMatches);
/// <summary>
/// Filters and fuzzy-ranks commands. With an empty query, returns filtered commands in input
/// order; otherwise ranks by relevance (title matches weighted above description/tags).
/// Filters and ranks commands. With an empty query, returns filtered commands in input order;
/// otherwise ranks by relevance. Titles allow fuzzy abbreviations ("sfc", "flsh dns"); descriptions
/// and tags need the query words as real substrings — matching them as loose subsequences made a
/// short query like "dns" hit most of the catalog. Matching ignores case and accents.
/// </summary>
public static class SearchCommandsUseCase
{
private const int TitleWeight = 20;
private const int ExactTitleScore = 300;
private const int TitleSubstringScore = 200;
private const int TitleWordsScore = 160;
private const int TitleFuzzyBase = 100;
private const int TagScore = 60;
private const int DescriptionScore = 40;
private const int WordStartBonus = 30;
public static IReadOnlyList<CommandSearchHit> Search(
IEnumerable<SearchableCommand> commands,
@@ -74,56 +91,145 @@ public static class SearchCommandsUseCase
ArgumentNullException.ThrowIfNull(commands);
var trimmed = query?.Trim() ?? string.Empty;
var hasQuery = trimmed.Length > 0;
var hits = new List<CommandSearchHit>();
foreach (var item in commands)
var filtered = filter is null ? commands : commands.Where(c => filter.Matches(c.Command));
if (trimmed.Length == 0)
{
if (filter is not null && !filter.Matches(item.Command))
return filtered.Select(c => new CommandSearchHit(c.Command, 0, [])).ToList();
}
var foldedQuery = TextFolding.Fold(trimmed);
var words = foldedQuery.Split(' ', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);
var hits = new List<CommandSearchHit>();
foreach (var item in filtered)
{
var (titleScore, titleIndices) = MatchTitle(item, trimmed, foldedQuery, words);
var score = Math.Max(titleScore, Math.Max(MatchTags(item, words), MatchDescription(item, words)));
if (score > 0)
{
continue;
hits.Add(new CommandSearchHit(item.Command, score, titleIndices));
}
}
if (!hasQuery)
// OrderByDescending is stable: equal scores keep catalog order.
return hits.OrderByDescending(h => h.Score).ToList();
}
private static (int Score, IReadOnlyList<int> Indices) MatchTitle(SearchableCommand item, string query, string foldedQuery, string[] words)
{
var title = item.FoldedTitle;
if (string.Equals(title, foldedQuery, StringComparison.Ordinal))
{
return (ExactTitleScore, Enumerable.Range(0, title.Length).ToList());
}
var index = BestOccurrence(title, foldedQuery);
if (index >= 0)
{
var score = TitleSubstringScore + (IsWordStart(title, index) ? WordStartBonus : 0) - Math.Min(index, 20);
return (score, Enumerable.Range(index, foldedQuery.Length).ToList());
}
if (words.Length > 1)
{
var indices = new List<int>();
var score = TitleWordsScore;
foreach (var word in words)
{
hits.Add(new CommandSearchHit(item.Command, 0, []));
continue;
}
var titleMatch = FuzzyMatcher.Match(item.Title, trimmed);
var best = int.MinValue;
if (titleMatch is { } tm)
{
best = tm.Score + TitleWeight;
}
if (FuzzyMatcher.Match(item.Description, trimmed) is { } dm)
{
best = Math.Max(best, dm.Score);
}
foreach (var tag in item.Tags)
{
if (FuzzyMatcher.Match(tag, trimmed) is { } tagMatch)
var at = BestOccurrence(title, word);
if (at < 0)
{
best = Math.Max(best, tagMatch.Score);
indices.Clear();
break;
}
score += IsWordStart(title, at) ? 10 : 0;
indices.AddRange(Enumerable.Range(at, word.Length));
}
if (indices.Count > 0)
{
return (score, indices.Distinct().Order().ToList());
}
}
if (FuzzyMatcher.Match(item.Title, query) is { } fuzzy
&& fuzzy.Score >= FuzzyMatcher.MinimumUsefulScore(foldedQuery.Length))
{
return (TitleFuzzyBase + fuzzy.Score, fuzzy.MatchedIndices);
}
return (0, []);
}
/// <summary>Every query word must start (or exactly equal) some tag.</summary>
private static int MatchTags(SearchableCommand item, string[] words)
{
var score = 0;
foreach (var word in words)
{
var best = 0;
foreach (var tag in item.FoldedTags)
{
if (string.Equals(tag, word, StringComparison.Ordinal))
{
best = Math.Max(best, TagScore + 10);
}
else if (tag.StartsWith(word, StringComparison.Ordinal))
{
best = Math.Max(best, TagScore);
}
}
if (best == int.MinValue)
if (best == 0)
{
continue;
return 0;
}
hits.Add(new CommandSearchHit(item.Command, best, titleMatch?.MatchedIndices ?? []));
score = Math.Max(score, best);
}
if (hasQuery)
{
hits.Sort(static (a, b) => b.Score.CompareTo(a.Score));
}
return hits;
return score;
}
/// <summary>Every query word must appear in the description as a real substring.</summary>
private static int MatchDescription(SearchableCommand item, string[] words)
{
var description = item.FoldedDescription;
var score = DescriptionScore;
foreach (var word in words)
{
var at = BestOccurrence(description, word);
if (at < 0)
{
return 0;
}
score += IsWordStart(description, at) ? 5 : 0;
}
return score;
}
/// <summary>The first occurrence of <paramref name="value"/> at a word start, else the first occurrence (-1 if none).</summary>
private static int BestOccurrence(string text, string value)
{
var first = -1;
for (var at = text.IndexOf(value, StringComparison.Ordinal); at >= 0; at = text.IndexOf(value, at + 1, StringComparison.Ordinal))
{
if (IsWordStart(text, at))
{
return at;
}
if (first < 0)
{
first = at;
}
}
return first;
}
private static bool IsWordStart(string text, int index) => index == 0 || !char.IsLetterOrDigit(text[index - 1]);
}
@@ -0,0 +1,49 @@
using System.Globalization;
using System.Text;
namespace CommandForge.Application.Search;
/// <summary>
/// Accent- and case-insensitive text for search: "Dọn dẹp" folds to "don dep", "Đặt" to "dat".
/// Folding works one character at a time, so index i of the result is index i of the input —
/// highlighting maps matches straight back onto the displayed text.
/// </summary>
public static class TextFolding
{
/// <summary>Folds <paramref name="text"/>, preserving its length.</summary>
public static string Fold(string text)
{
ArgumentNullException.ThrowIfNull(text);
return string.Create(text.Length, text, static (span, source) =>
{
for (var i = 0; i < source.Length; i++)
{
span[i] = FoldChar(source[i]);
}
});
}
/// <summary>Folds a single character: lower-case, without diacritics.</summary>
public static char FoldChar(char c)
{
if (c < 128)
{
return char.ToLowerInvariant(c);
}
if (c is 'đ' or 'Đ')
{
return 'd';
}
foreach (var part in c.ToString().Normalize(NormalizationForm.FormD))
{
if (CharUnicodeInfo.GetUnicodeCategory(part) != UnicodeCategory.NonSpacingMark)
{
return char.ToLowerInvariant(part);
}
}
return c; // a lone combining mark stays as it is
}
}
@@ -5,35 +5,50 @@ namespace CommandForge.Application.Settings;
/// <summary>
/// The machine-portable subset of settings — appearance, behavior/safety preferences and favorites —
/// used for import/export and named profiles. Excludes machine-specific state (window placement,
/// accepted terms version, recent commands, execution history).
/// accepted terms version, recent commands, execution history). Properties are settable so the
/// source-generated serializer keeps these defaults for keys a file omits (init-only properties
/// would be reset to false/0 — e.g. silently turning off Caution confirmations).
/// </summary>
public sealed record PortableSettings
{
/// <summary>Schema version of the portable payload (for forward-compat).</summary>
public int Version { get; init; } = 1;
public int Version { get; set; } = 1;
public AppTheme Theme { get; init; } = AppTheme.System;
public AppTheme Theme { get; set; } = AppTheme.System;
public string Language { get; init; } = "";
public string Language { get; set; } = "";
public FontScale FontSize { get; init; } = FontScale.Medium;
public FontScale FontSize { get; set; } = FontScale.Medium;
public bool CollapseSidebarByDefault { get; init; }
public bool CollapseSidebarByDefault { get; set; }
public bool ShowAdminRestartBadges { get; init; } = true;
public bool ShowAdminRestartBadges { get; set; } = true;
public bool ConfirmCaution { get; init; } = true;
public bool ConfirmCaution { get; set; } = true;
public bool AutoCreateRestorePoint { get; init; } = true;
public bool AutoCreateRestorePoint { get; set; } = true;
public bool AutoScrollConsole { get; init; } = true;
public bool AutoScrollConsole { get; set; } = true;
public bool WarnOnCancel { get; init; } = true;
public bool WarnOnCancel { get; set; } = true;
public bool AutoCheckForUpdates { get; init; } = true;
public bool AutoCheckForUpdates { get; set; } = true;
public LogLevel LogLevel { get; init; } = LogLevel.Information;
public LogLevel LogLevel { get; set; } = LogLevel.Information;
/// <summary>Pinned favorite command ids, in pin order.</summary>
public IReadOnlyList<string> FavoriteCommandIds { get; init; } = [];
public IReadOnlyList<string> FavoriteCommandIds { get; set; } = [];
/// <summary>
/// Repairs what an imported or hand-edited file may contain: null lists or language, enum
/// values outside the defined range, blank or duplicate favorite ids.
/// </summary>
public PortableSettings Normalized() => this with
{
Language = Language ?? string.Empty,
Theme = Enum.IsDefined(Theme) ? Theme : AppTheme.System,
FontSize = Enum.IsDefined(FontSize) ? FontSize : FontScale.Medium,
LogLevel = Enum.IsDefined(LogLevel) ? LogLevel : LogLevel.Information,
FavoriteCommandIds = FavoriteCommandIds?.Where(id => !string.IsNullOrWhiteSpace(id)).Distinct(StringComparer.Ordinal).ToList() ?? [],
};
}
@@ -17,13 +17,7 @@ public static class RecentCommands
ArgumentException.ThrowIfNullOrEmpty(commandId);
var result = new List<string>(current.Count + 1) { commandId };
foreach (var id in current)
{
if (!string.Equals(id, commandId, StringComparison.Ordinal))
{
result.Add(id);
}
}
result.AddRange(current.Where(id => !string.Equals(id, commandId, StringComparison.Ordinal)));
if (result.Count > MaxItems)
{
@@ -39,6 +39,7 @@ public static class SettingsTransfer
ArgumentNullException.ThrowIfNull(portable);
ArgumentNullException.ThrowIfNull(settings);
portable = portable.Normalized();
settings.Theme = portable.Theme;
settings.Language = portable.Language;
settings.FontSize = portable.FontSize;
@@ -6,9 +6,10 @@ namespace CommandForge.Application.Updates;
/// <summary>
/// Pure mapping of an HTTP status / exception to an <see cref="UpdateError"/>. No I/O, so it is
/// unit-testable without a network. GitHub uses 403 (primary rate limit, with an
/// <c>X-RateLimit-Remaining</c> header) and 429 (secondary); there is NO 419 (that is a Laravel
/// CSRF code, not GitHub) so it must fall through to <see cref="UpdateError.Unknown"/>.
/// unit-testable without a network. The feed (<see cref="ProductLinks.UpdateFeed"/>) is served by
/// Cloudflare, whose edge answers 403 when it refuses a request and 429 when it rate-limits; both
/// mean "try again later". There is NO 419 (that is a Laravel CSRF code, not an HTTP standard), so
/// it must fall through to <see cref="UpdateError.Unknown"/>.
/// </summary>
public static class UpdateErrorMapper
{
@@ -18,7 +19,7 @@ public static class UpdateErrorMapper
if (status is null)
{
// No status: a transport failure (no network/DNS), a socket error, or a timeout.
return exception is HttpRequestException or SocketException or TaskCanceledException
return exception is not null && IsTransportFailure(exception)
? UpdateError.Offline
: UpdateError.Unknown;
}
@@ -32,4 +33,48 @@ public static class UpdateErrorMapper
_ => UpdateError.Unknown, // incl. 419
};
}
/// <summary>
/// Maps an exception from the update library, looking through wrapper and aggregate
/// exceptions for the HTTP status or transport failure underneath.
/// </summary>
public static UpdateError Map(Exception exception)
{
ArgumentNullException.ThrowIfNull(exception);
var all = Flatten(exception).ToList();
var http = all.OfType<HttpRequestException>().FirstOrDefault(e => e.StatusCode is not null);
if (http is not null)
{
return Map(http.StatusCode, http);
}
return all.Exists(IsTransportFailure) ? UpdateError.Offline : UpdateError.Unknown;
}
// HttpClient timeouts surface as TaskCanceledException (with an inner TimeoutException).
private static bool IsTransportFailure(Exception exception)
=> exception is HttpRequestException or SocketException or TimeoutException or TaskCanceledException;
private static IEnumerable<Exception> Flatten(Exception root)
{
var pending = new Stack<Exception>();
pending.Push(root);
while (pending.Count > 0)
{
var current = pending.Pop();
yield return current;
if (current is AggregateException aggregate)
{
foreach (var inner in aggregate.InnerExceptions)
{
pending.Push(inner);
}
}
else if (current.InnerException is { } inner)
{
pending.Push(inner);
}
}
}
}
@@ -19,11 +19,15 @@ public sealed class CheckForUpdateUseCase
/// <summary>Whether updates apply to this install (false in dev/unpackaged).</summary>
public bool IsSupported => _updates.IsUpdateSupported;
/// <summary>Checks GitHub Releases for a newer version.</summary>
/// <summary>Checks the release feed for a newer version.</summary>
public Task<UpdateCheckResult> ExecuteAsync(CancellationToken cancellationToken = default)
=> _updates.CheckForUpdatesAsync(cancellationToken);
/// <summary>Downloads and applies the pending update, then restarts.</summary>
public Task<UpdateError> DownloadAndApplyAsync(IProgress<int>? progress, CancellationToken cancellationToken = default)
=> _updates.DownloadAndApplyAsync(progress, cancellationToken);
/// <summary>Downloads the pending update.</summary>
public Task<UpdateError> DownloadAsync(IProgress<int>? progress, CancellationToken cancellationToken = default)
=> _updates.DownloadAsync(progress, cancellationToken);
/// <summary>Applies the downloaded update and restarts.</summary>
public Task<UpdateError> ApplyAndRestartAsync(CancellationToken cancellationToken = default)
=> _updates.ApplyAndRestartAsync(cancellationToken);
}
@@ -15,20 +15,37 @@ public sealed class RunCommandUseCase
public RunCommandUseCase(ICommandExecutor executor, IElevationService elevation)
{
ArgumentNullException.ThrowIfNull(executor);
ArgumentNullException.ThrowIfNull(elevation);
_executor = executor;
_elevation = elevation;
}
/// <summary>Runs <paramref name="command"/>, streaming output, choosing executor by <c>RequiresAdmin</c>.</summary>
public Task<ExecutionResult> RunAsync(
/// <summary>
/// Runs <paramref name="command"/>, streaming output, choosing the executor by <c>RequiresAdmin</c>.
/// The output channel is always completed — even when the run throws — so a reader never waits forever.
/// </summary>
public async Task<ExecutionResult> RunAsync(
CommandDefinition command,
ChannelWriter<OutputLine> output,
CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(command);
ArgumentNullException.ThrowIfNull(output);
return command.RequiresAdmin
? _elevation.RunElevatedAsync(command, output, cancellationToken)
: _executor.ExecuteAsync(command, output, cancellationToken);
try
{
return command.RequiresAdmin
? await _elevation.RunElevatedAsync(command, output, cancellationToken).ConfigureAwait(false)
: await _executor.ExecuteAsync(command, output, cancellationToken).ConfigureAwait(false);
}
catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested)
{
return new ExecutionResult { ExitCode = -1, Success = false, Duration = TimeSpan.Zero, Cancelled = true };
}
finally
{
output.TryComplete();
}
}
}
@@ -25,14 +25,60 @@ public static class UserCommandFactory
{
Id = IdPrefix + command.Id,
CategoryId = "user",
TitleKey = command.Name,
DescriptionKey = command.Name,
// Not resource keys: the shell displays user commands by name. A name that happens to
// equal a resource key (e.g. "AppTitle") must not be translated into that resource.
TitleKey = IdPrefix + command.Id,
DescriptionKey = IdPrefix + command.Id,
Executable = command.Executable,
ArgsTemplate = command.Arguments,
ArgsTemplate = NormalizeArguments(command.Executable, command.Arguments),
ExecutionMode = ExecutionMode.Capture,
RequiresAdmin = false, // INVARIANT — a user command must never elevate.
DangerLevel = DangerLevel.Caution,
Restart = RestartPolicy.No,
};
}
/// <summary>
/// Normalizes arguments so a one-shot command actually runs and then exits. <c>cmd.exe</c>
/// without <c>/c</c> (or <c>/k</c>) opens an interactive shell that blocks forever waiting on
/// stdin, so for cmd we prepend <c>/c</c>. Other executables (e.g. powershell) are left as-is.
/// </summary>
public static string NormalizeArguments(string executable, string? arguments)
{
ArgumentNullException.ThrowIfNull(executable);
var args = arguments ?? string.Empty;
if (IsCmd(executable) && !HasCmdRunSwitch(args))
{
return args.Length == 0 ? "/c" : "/c " + args;
}
return args;
}
private static bool IsCmd(string executable)
=> string.Equals(Path.GetFileNameWithoutExtension(executable.Trim().Trim('"')), "cmd", StringComparison.OrdinalIgnoreCase);
/// <summary>True when a /c or /k switch appears among the leading switches (e.g. "/q /c dir").</summary>
private static bool HasCmdRunSwitch(string arguments)
{
foreach (var token in arguments.Split(' ', StringSplitOptions.RemoveEmptyEntries))
{
if (!token.StartsWith('/'))
{
return false; // switches come first; the command text starts here
}
if (StartsWithSwitch(token, "/c") || StartsWithSwitch(token, "/k"))
{
return true;
}
}
return false;
}
private static bool StartsWithSwitch(string text, string flag)
=> text.StartsWith(flag, StringComparison.OrdinalIgnoreCase)
&& (text.Length == flag.Length || char.IsWhiteSpace(text[flag.Length]));
}
@@ -64,4 +64,23 @@ public sealed record CommandDefinition
/// <summary>Free-form search tags.</summary>
public IReadOnlyList<string> Tags { get; init; } = [];
/// <summary>
/// Inclusive lowest Windows build this command applies to (e.g. <c>22000</c> for Windows 11+).
/// <see langword="null"/> means no lower bound.
/// </summary>
public int? MinOsBuild { get; init; }
/// <summary>
/// Inclusive highest Windows build this command applies to (e.g. <c>19045</c> for Windows 10 only).
/// <see langword="null"/> means no upper bound.
/// </summary>
public int? MaxOsBuild { get; init; }
/// <summary>
/// Whether this command applies to the given OS build. Pure logic (no Win32) so the presentation
/// layer can hide commands that do not apply to the current Windows version.
/// </summary>
public bool AppliesToOsBuild(int build)
=> (MinOsBuild is null || build >= MinOsBuild) && (MaxOsBuild is null || build <= MaxOsBuild);
}
+12 -3
View File
@@ -5,12 +5,21 @@ namespace CommandForge.Domain;
/// </summary>
public enum DangerLevel
{
/// <summary>Read-only / informational, no risk.</summary>
/// <summary>
/// No risk of losing data: read-only queries, opening a tool or settings page, or a small
/// preference change that is undone the same way it was made.
/// </summary>
Safe,
/// <summary>Changes the system but is recoverable / low risk.</summary>
/// <summary>
/// Changes system state (services, registry, caches, boot-time checks); recoverable, but undoing
/// it may take effort. Confirmed before running unless the user turned that off.
/// </summary>
Caution,
/// <summary>May cause data loss or instability; requires strict confirmation.</summary>
/// <summary>
/// May lose data, remove a rollback option or leave Windows unstable. Always needs a typed
/// confirmation, which the user cannot turn off.
/// </summary>
Dangerous,
}
-22
View File
@@ -1,22 +0,0 @@
namespace CommandForge.Domain;
/// <summary>
/// The kind of executable a command runs through. Maps the <c>executable</c> field of the catalog.
/// </summary>
public enum ExecutableKind
{
/// <summary>cmd.exe</summary>
Cmd,
/// <summary>powershell.exe / pwsh</summary>
PowerShell,
/// <summary>winget</summary>
Winget,
/// <summary>dism.exe</summary>
Dism,
/// <summary>A direct path to an executable.</summary>
Direct,
}
+2 -4
View File
@@ -18,13 +18,11 @@ public sealed record ExecutionResult
public required TimeSpan Duration { get; init; }
/// <summary>
/// Whether a system restart is required to finish (e.g. exit code 3010 or a regex match).
/// Whether a system restart is required to finish (exit code 3010, a restart-always command, or
/// an output-regex match).
/// </summary>
public bool RequiresRestart { get; init; }
/// <summary>Whether the run was cancelled by the user (process tree killed).</summary>
public bool Cancelled { get; init; }
/// <summary>Captured stdout/stderr lines, in order.</summary>
public IReadOnlyList<string> OutputLines { get; init; } = [];
}
@@ -33,6 +33,8 @@ internal sealed record CommandDto
public string? DocUrl { get; init; }
public string[]? Tags { get; init; }
public RegistryValueDto[]? AffectedRegistryValues { get; init; }
public int? MinOsBuild { get; init; }
public int? MaxOsBuild { get; init; }
}
/// <summary>JSON shape of a registry-value reference (for before/after comparison).</summary>
@@ -1,6 +1,8 @@
using System.Buffers;
using System.Text.Json;
using System.Text.Json.Serialization.Metadata;
using System.Text.RegularExpressions;
using CommandForge.Application;
using CommandForge.Application.Ports;
using CommandForge.Domain;
@@ -13,19 +15,36 @@ public sealed record CatalogLoadResult(
IReadOnlyList<string> Errors);
/// <summary>
/// Reads the embedded <c>categories.json</c> / <c>commands.json</c>, validates them, and
/// maps to Domain entities. Structural validation only — the cross-check that title/desc
/// resource keys exist lives in the test project (it owns the .resx).
/// Reads the embedded <c>categories.json</c> / <c>commands.json</c>, validates them, and maps to
/// Domain entities. A record that fails validation is reported and left out — never loaded half
/// right. The cross-check that title/desc resource keys exist lives in the test project (it owns
/// the .resx).
/// </summary>
public static class CatalogLoader
{
private const string ResourcePrefix = "CommandForge.Infrastructure.Catalog.";
// A catalog executable is a bare program name ("dism", "services.msc"); the resolver pins it to
// the system directories. Paths, quotes and spaces would sidestep that.
private static readonly SearchValues<char> NotInProgramName = SearchValues.Create(" \t\"/\\");
/// <summary>Loads and validates the catalog embedded in this assembly.</summary>
public static CatalogLoadResult LoadEmbedded()
{
var categories = Deserialize("categories.json", CatalogJsonContext.Default.CategoryDtoArray);
var commands = Deserialize("commands.json", CatalogJsonContext.Default.CommandDtoArray);
CategoryDto[] categories;
CommandDto[] commands;
try
{
categories = Deserialize("categories.json", CatalogJsonContext.Default.CategoryDtoArray);
commands = Deserialize("commands.json", CatalogJsonContext.Default.CommandDtoArray);
}
catch (JsonException ex)
{
// Tests make this unreachable for a released build; still, an empty catalog plus an error
// in the log and the Debug panel beats an app (or Elevator) that cannot start at all.
return new CatalogLoadResult([], [], [$"The embedded catalog is not valid JSON: {ex.Message}"]);
}
return Build(categories, commands);
}
@@ -43,13 +62,45 @@ public static class CatalogLoader
internal static CatalogLoadResult Build(CategoryDto[] categoryDtos, CommandDto[] commandDtos)
{
var errors = new List<string>();
var categories = BuildCategories(categoryDtos, errors);
var categoryIds = categories.Select(c => c.Id).ToHashSet(StringComparer.Ordinal);
var commands = new List<CommandDefinition>();
var seenIds = new HashSet<string>(StringComparer.Ordinal);
foreach (var dto in commandDtos)
{
if (string.IsNullOrWhiteSpace(dto.Id)) { errors.Add("A command has an empty id."); continue; }
if (!seenIds.Add(dto.Id)) { errors.Add($"Duplicate command id '{dto.Id}'."); continue; }
var problem = FindStructuralProblem(dto, categoryIds) ?? FindBehaviorProblem(dto);
if (problem is not null) { errors.Add($"Command '{dto.Id}' {problem}"); continue; }
commands.Add(ToDefinition(dto));
}
// Only commands that were actually loaded can be reverted to; a dangling id would offer an
// Undo that cannot run.
var loadedIds = commands.Select(c => c.Id).ToHashSet(StringComparer.Ordinal);
for (var i = 0; i < commands.Count; i++)
{
if (commands[i].RevertCommandId is { } revertId && !loadedIds.Contains(revertId))
{
errors.Add($"Command '{commands[i].Id}' has revertCommandId '{revertId}' that does not exist.");
commands[i] = commands[i] with { RevertCommandId = null };
}
}
return new CatalogLoadResult(categories, commands, errors);
}
private static List<CommandCategory> BuildCategories(CategoryDto[] categoryDtos, List<string> errors)
{
var categories = new List<CommandCategory>();
var categoryIds = new HashSet<string>(StringComparer.Ordinal);
var seenIds = new HashSet<string>(StringComparer.Ordinal);
foreach (var dto in categoryDtos)
{
if (string.IsNullOrWhiteSpace(dto.Id)) { errors.Add("A category has an empty id."); continue; }
if (!categoryIds.Add(dto.Id)) { errors.Add($"Duplicate category id '{dto.Id}'."); continue; }
if (!seenIds.Add(dto.Id)) { errors.Add($"Duplicate category id '{dto.Id}'."); continue; }
if (string.IsNullOrWhiteSpace(dto.TitleKey)) { errors.Add($"Category '{dto.Id}' is missing titleKey."); continue; }
categories.Add(new CommandCategory
@@ -61,60 +112,71 @@ public static class CatalogLoader
});
}
var commands = new List<CommandDefinition>();
var commandIds = new HashSet<string>(StringComparer.Ordinal);
foreach (var dto in commandDtos)
{
if (string.IsNullOrWhiteSpace(dto.Id)) { errors.Add("A command has an empty id."); continue; }
if (!commandIds.Add(dto.Id)) { errors.Add($"Duplicate command id '{dto.Id}'."); continue; }
if (string.IsNullOrWhiteSpace(dto.CategoryId)) { errors.Add($"Command '{dto.Id}' is missing categoryId."); continue; }
if (!categoryIds.Contains(dto.CategoryId)) { errors.Add($"Command '{dto.Id}' references unknown categoryId '{dto.CategoryId}'."); continue; }
if (string.IsNullOrWhiteSpace(dto.TitleKey)) { errors.Add($"Command '{dto.Id}' is missing titleKey."); continue; }
if (string.IsNullOrWhiteSpace(dto.DescriptionKey)) { errors.Add($"Command '{dto.Id}' is missing descriptionKey."); continue; }
if (string.IsNullOrWhiteSpace(dto.Executable)) { errors.Add($"Command '{dto.Id}' is missing executable."); continue; }
if (dto.Restart == RestartPolicy.FromOutputRegex && !IsValidRegex(dto.RestartRegex)) { errors.Add($"Command '{dto.Id}' has an invalid restartRegex."); continue; }
commands.Add(new CommandDefinition
{
Id = dto.Id,
CategoryId = dto.CategoryId,
TitleKey = dto.TitleKey,
DescriptionKey = dto.DescriptionKey,
Icon = dto.Icon,
Executable = dto.Executable,
ArgsTemplate = dto.ArgsTemplate ?? string.Empty,
ExecutionMode = dto.ExecutionMode,
RequiresAdmin = dto.RequiresAdmin,
DangerLevel = dto.DangerLevel,
ConfirmBeforeRun = dto.ConfirmBeforeRun,
CreatesRestorePoint = dto.CreatesRestorePoint,
Restart = dto.Restart,
RestartRegex = dto.RestartRegex,
RevertCommandId = dto.RevertCommandId,
EstimatedDuration = dto.EstimatedDuration,
DocUrl = dto.DocUrl,
Tags = dto.Tags ?? [],
AffectedRegistryValues = dto.AffectedRegistryValues is null
? []
: dto.AffectedRegistryValues
.Where(r => !string.IsNullOrWhiteSpace(r.Path))
.Select(r => new RegistryValueRef { Path = r.Path!, Name = r.Name ?? string.Empty })
.ToList(),
});
}
foreach (var command in commands)
{
if (!string.IsNullOrWhiteSpace(command.RevertCommandId) && !commandIds.Contains(command.RevertCommandId))
{
errors.Add($"Command '{command.Id}' has revertCommandId '{command.RevertCommandId}' that does not exist.");
}
}
categories.Sort((a, b) => a.Order.CompareTo(b.Order));
return new CatalogLoadResult(categories, commands, errors);
return categories;
}
/// <summary>A missing or dangling field, as the end of an error sentence; <see langword="null"/> when there is none.</summary>
private static string? FindStructuralProblem(CommandDto dto, HashSet<string> categoryIds)
{
if (string.IsNullOrWhiteSpace(dto.CategoryId)) { return "is missing categoryId."; }
if (!categoryIds.Contains(dto.CategoryId)) { return $"references unknown categoryId '{dto.CategoryId}'."; }
if (string.IsNullOrWhiteSpace(dto.TitleKey)) { return "is missing titleKey."; }
if (string.IsNullOrWhiteSpace(dto.DescriptionKey)) { return "is missing descriptionKey."; }
if (string.IsNullOrWhiteSpace(dto.Executable)) { return "is missing executable."; }
if (dto.Executable.AsSpan().IndexOfAny(NotInProgramName) >= 0) { return "has an executable that is not a plain program name (arguments belong in argsTemplate)."; }
if (dto.MinOsBuild is <= 0) { return "has a non-positive minOsBuild."; }
if (dto.MaxOsBuild is <= 0) { return "has a non-positive maxOsBuild."; }
if (dto.MinOsBuild is { } minBuild && dto.MaxOsBuild is { } maxBuild && maxBuild < minBuild) { return $"has maxOsBuild ({maxBuild}) less than minOsBuild ({minBuild})."; }
return null;
}
/// <summary>Settings that contradict each other or the safety rules; <see langword="null"/> when there are none.</summary>
private static string? FindBehaviorProblem(CommandDto dto)
{
var unknownTokens = ArgumentTokens.FindUnknown(dto.ArgsTemplate ?? string.Empty);
if (unknownTokens.Count > 0) { return $"uses unknown argument token(s) {string.Join(", ", unknownTokens)}."; }
if (dto.DangerLevel != DangerLevel.Safe && !dto.ConfirmBeforeRun) { return $"is {dto.DangerLevel} but does not set confirmBeforeRun."; }
if (dto.ExecutionMode == ExecutionMode.Launch && dto.Restart is RestartPolicy.FromExitCode or RestartPolicy.FromOutputRegex)
{
return $"cannot use restart policy {dto.Restart} in Launch mode (its exit code and output are not captured).";
}
if (dto.Restart == RestartPolicy.FromOutputRegex && !IsValidRegex(dto.RestartRegex)) { return "has an invalid restartRegex."; }
if (dto.Restart != RestartPolicy.FromOutputRegex && !string.IsNullOrEmpty(dto.RestartRegex)) { return $"has a restartRegex but its restart policy is {dto.Restart}."; }
return null;
}
private static CommandDefinition ToDefinition(CommandDto dto) => new()
{
Id = dto.Id!,
CategoryId = dto.CategoryId!,
TitleKey = dto.TitleKey!,
DescriptionKey = dto.DescriptionKey!,
Icon = dto.Icon,
Executable = dto.Executable!,
ArgsTemplate = dto.ArgsTemplate ?? string.Empty,
ExecutionMode = dto.ExecutionMode,
RequiresAdmin = dto.RequiresAdmin,
DangerLevel = dto.DangerLevel,
ConfirmBeforeRun = dto.ConfirmBeforeRun,
CreatesRestorePoint = dto.CreatesRestorePoint,
Restart = dto.Restart,
RestartRegex = dto.RestartRegex,
RevertCommandId = string.IsNullOrWhiteSpace(dto.RevertCommandId) ? null : dto.RevertCommandId,
EstimatedDuration = dto.EstimatedDuration,
DocUrl = dto.DocUrl,
Tags = dto.Tags ?? [],
AffectedRegistryValues = dto.AffectedRegistryValues is null
? []
: dto.AffectedRegistryValues
.Where(r => !string.IsNullOrWhiteSpace(r.Path))
.Select(r => new RegistryValueRef { Path = r.Path!, Name = r.Name ?? string.Empty })
.ToList(),
MinOsBuild = dto.MinOsBuild,
MaxOsBuild = dto.MaxOsBuild,
};
private static bool IsValidRegex(string? pattern)
{
if (string.IsNullOrWhiteSpace(pattern))
@@ -124,7 +186,7 @@ public static class CatalogLoader
try
{
_ = Regex.Match(string.Empty, pattern);
_ = Regex.Match(string.Empty, pattern, RegexOptions.None, TimeSpan.FromSeconds(1));
return true;
}
catch (ArgumentException)
@@ -8,5 +8,10 @@
{ "id": "system-info", "titleKey": "Cat_system-info", "icon": "Information", "order": 7 },
{ "id": "diagnostics", "titleKey": "Cat_diagnostics", "icon": "Stethoscope", "order": 8 },
{ "id": "security-privacy", "titleKey": "Cat_security-privacy", "icon": "ShieldLock", "order": 9 },
{ "id": "developer", "titleKey": "Cat_developer", "icon": "CodeBraces", "order": 10 }
{ "id": "developer", "titleKey": "Cat_developer", "icon": "CodeBraces", "order": 10 },
{ "id": "storage", "titleKey": "Cat_storage", "icon": "Harddisk", "order": 11 },
{ "id": "services-startup", "titleKey": "Cat_services-startup", "icon": "Cog", "order": 12 },
{ "id": "devices", "titleKey": "Cat_devices", "icon": "Devices", "order": 13 },
{ "id": "backup-recovery", "titleKey": "Cat_backup-recovery", "icon": "BackupRestore", "order": 14 },
{ "id": "accounts", "titleKey": "Cat_accounts", "icon": "AccountMultiple", "order": 15 }
]
File diff suppressed because it is too large. Load diff
@@ -25,13 +25,14 @@
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.DependencyInjection.Abstractions" Version="10.0.9" />
<PackageReference Include="Microsoft.Windows.CsWin32" Version="0.3.298">
<PackageReference Include="Microsoft.Extensions.DependencyInjection.Abstractions" Version="10.0.15" />
<PackageReference Include="Microsoft.Windows.CsWin32" Version="0.3.371">
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
<PrivateAssets>all</PrivateAssets>
</PackageReference>
<PackageReference Include="Serilog" Version="4.3.1" />
<PackageReference Include="Velopack" Version="1.2.0" />
<PackageReference Include="Serilog" Version="4.4.0" />
<!-- Keep in lockstep with the vpk tool version in .config/dotnet-tools.json. -->
<PackageReference Include="Velopack" Version="1.2.161" />
</ItemGroup>
</Project>
@@ -1,9 +1,11 @@
using System.ComponentModel;
using System.Diagnostics;
using System.IO.Pipes;
using System.Text.Json;
using System.Threading.Channels;
using CommandForge.Application.Ports;
using CommandForge.Domain;
using Serilog;
namespace CommandForge.Infrastructure.Elevation;
@@ -16,34 +18,86 @@ internal sealed class BrokerElevationService : IElevationService, IDisposable
{
private static readonly TimeSpan ConnectTimeout = TimeSpan.FromSeconds(60);
// How long a cancelled command may take to wind down before the whole session is dropped.
private static readonly TimeSpan CancelGracePeriod = TimeSpan.FromSeconds(10);
private static readonly TimeSpan ExitTimeout = TimeSpan.FromSeconds(5);
private readonly ILogger _log = Log.ForContext<BrokerElevationService>();
private readonly SemaphoreSlim _connectLock = new(1, 1);
private NamedPipeServerStream? _server;
private PipeMessageChannel? _channel;
private Process? _elevator;
public bool IsElevationAvailable => OperatingSystem.IsWindows();
/// <inheritdoc />
public bool IsSessionActive => _channel is not null && _server is { IsConnected: true };
/// <inheritdoc />
public event EventHandler? SessionChanged;
/// <inheritdoc />
public async Task<ExecutionResult> RunElevatedAsync(
CommandDefinition command,
ChannelWriter<OutputLine> output,
CancellationToken cancellationToken)
CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(command);
ArgumentNullException.ThrowIfNull(output);
try
{
return await RunCoreAsync(command, output, cancellationToken);
}
finally
{
output.TryComplete();
}
}
/// <inheritdoc />
public async Task EndSessionAsync(CancellationToken cancellationToken = default)
{
await _connectLock.WaitAsync(cancellationToken);
try
{
var elevator = _elevator;
_elevator = null;
ResetConnection(); // closing the pipe makes the Elevator stop its command and exit
if (elevator is not null)
{
await WaitForExitAsync(elevator, cancellationToken);
}
}
finally
{
_connectLock.Release();
}
}
private async Task<ExecutionResult> RunCoreAsync(CommandDefinition command, ChannelWriter<OutputLine> output, CancellationToken cancellationToken)
{
PipeMessageChannel channel;
try
{
channel = await EnsureConnectedAsync(cancellationToken);
}
catch (Exception ex) when (ex is Win32Exception or TimeoutException or IOException or InvalidOperationException)
catch (OperationCanceledException)
{
return CancelledResult(); // cancelled while waiting for UAC / the Elevator to connect
}
catch (Exception ex) when (ex is Win32Exception or TimeoutException or IOException or InvalidOperationException or UnauthorizedAccessException)
{
_log.Warning(ex, "Elevation unavailable for {CommandId}.", command.Id);
return await FailAsync(output, $"Elevation unavailable: {ex.Message}");
}
using var cancelRegistration = cancellationToken.Register(
static state => _ = SendCancelAsync((PipeMessageChannel)state!),
channel);
// Reads end when the Elevator answers — or CancelGracePeriod after the user cancels, if it doesn't.
using var readCancel = new CancellationTokenSource();
using var cancelRegistration = cancellationToken.Register(() =>
{
_ = SendCancelAsync(channel);
readCancel.CancelAfter(CancelGracePeriod);
});
try
{
@@ -54,32 +108,37 @@ internal sealed class BrokerElevationService : IElevationService, IDisposable
while (true)
{
var message = await channel.ReadAsync(ElevationJsonContext.Default.ElevationMessage, CancellationToken.None);
var message = await channel.ReadAsync(ElevationJsonContext.Default.ElevationMessage, readCancel.Token);
if (message is null)
{
ResetConnection();
return await FailAsync(output, "The Elevator closed the connection unexpectedly.");
}
if (message.Kind == ElevationMessageKind.Output)
switch (message.Kind)
{
await output.WriteAsync(new OutputLine(message.Text ?? string.Empty, message.IsError), CancellationToken.None);
continue;
case ElevationMessageKind.Output:
await output.WriteAsync(new OutputLine(message.Text ?? string.Empty, message.IsError), CancellationToken.None);
break;
case ElevationMessageKind.Log:
LogFromElevator(message);
break;
default:
return ToResult(message);
}
output.TryComplete();
return new ExecutionResult
{
ExitCode = message.ExitCode,
Success = message.Success,
Duration = TimeSpan.FromMilliseconds(message.DurationMs),
RequiresRestart = message.RequiresRestart,
Cancelled = message.Cancelled,
};
}
}
catch (IOException ex)
catch (OperationCanceledException ex)
{
// The Elevator did not acknowledge the cancel in time; dropping the pipe makes it kill
// the command and exit, and the next admin command starts a fresh session.
_log.Warning(ex, "Elevator did not stop {CommandId} within {Seconds}s of cancel; ending the elevated session.", command.Id, CancelGracePeriod.TotalSeconds);
ResetConnection();
return CancelledResult();
}
catch (Exception ex) when (ex is IOException or ObjectDisposedException or JsonException)
{
_log.Warning(ex, "Elevation pipe failed while running {CommandId}.", command.Id);
ResetConnection();
return await FailAsync(output, $"Elevation pipe error: {ex.Message}");
}
@@ -128,13 +187,21 @@ internal sealed class BrokerElevationService : IElevationService, IDisposable
throw new TimeoutException("The Elevator did not connect in time.");
}
// The ACL admits any process of this user; only the Elevator we just started may talk to us.
if (!PeerVerifier.IsExpectedClient(server, _elevator.Id))
{
throw new InvalidOperationException("An unexpected process connected to the elevation pipe.");
}
_server = server;
_channel = new PipeMessageChannel(server);
_log.Information("Elevated session started (Elevator process {ProcessId}).", _elevator.Id);
SessionChanged?.Invoke(this, EventArgs.Empty);
return _channel;
}
catch
{
server.Dispose();
await server.DisposeAsync();
_elevator?.Dispose();
_elevator = null;
throw;
@@ -146,6 +213,50 @@ internal sealed class BrokerElevationService : IElevationService, IDisposable
}
}
private void LogFromElevator(ElevationMessage message)
{
if (message.IsError)
{
_log.Warning("Elevator: {Message}", message.Text);
}
else
{
_log.Information("Elevator: {Message}", message.Text);
}
}
private async Task WaitForExitAsync(Process elevator, CancellationToken cancellationToken)
{
try
{
await elevator.WaitForExitAsync(cancellationToken).WaitAsync(ExitTimeout, cancellationToken);
}
catch (TimeoutException ex)
{
_log.Warning(ex, "The Elevator did not exit within {Seconds}s.", ExitTimeout.TotalSeconds);
}
catch (InvalidOperationException)
{
// No process handle (already gone) — nothing to wait for.
}
finally
{
elevator.Dispose();
}
}
private static ExecutionResult ToResult(ElevationMessage message) => new()
{
ExitCode = message.ExitCode,
Success = message.Success,
Duration = TimeSpan.FromMilliseconds(message.DurationMs),
RequiresRestart = message.RequiresRestart,
Cancelled = message.Cancelled,
};
private static ExecutionResult CancelledResult()
=> new() { ExitCode = -1, Success = false, Duration = TimeSpan.Zero, Cancelled = true };
private static async Task SendCancelAsync(PipeMessageChannel channel)
{
try
@@ -174,6 +285,7 @@ internal sealed class BrokerElevationService : IElevationService, IDisposable
private void ResetConnection()
{
var hadSession = _server is not null;
_channel?.Dispose();
_channel = null;
@@ -183,6 +295,11 @@ internal sealed class BrokerElevationService : IElevationService, IDisposable
_elevator?.Dispose();
_elevator = null;
if (hadSession)
{
SessionChanged?.Invoke(this, EventArgs.Empty);
}
}
public void Dispose()
@@ -0,0 +1,102 @@
namespace CommandForge.Infrastructure.Elevation;
/// <summary>
/// Builds the environment for processes the elevated Elevator starts. The Elevator inherits the
/// user's environment block, and a standard user can define per-user variables (HKCU\Environment)
/// that redirect what an elevated child loads or touches: <c>COR_PROFILER</c>/<c>CORECLR_*</c>
/// inject a DLL into .NET processes such as PowerShell, <c>PSModulePath</c> makes PowerShell
/// auto-load modules from the user's Documents folder, and <c>windir</c>/<c>SystemRoot</c> retarget
/// the recursive deletes some cleanup commands perform. So the child gets an allow-list: a few
/// harmless pass-through values plus system paths re-derived from trusted sources.
/// </summary>
internal static class ChildEnvironment
{
// Copied from the Elevator's own environment when present (identity / hardware / user folders).
private static readonly string[] PassThrough =
[
"APPDATA", "COMPUTERNAME", "HOMEDRIVE", "HOMEPATH", "LOCALAPPDATA", "LOGONSERVER",
"NUMBER_OF_PROCESSORS", "OS", "PROCESSOR_ARCHITECTURE", "PROCESSOR_IDENTIFIER",
"PROCESSOR_LEVEL", "PROCESSOR_REVISION", "SESSIONNAME", "TEMP", "TMP", "USERDNSDOMAIN",
"USERDOMAIN", "USERDOMAIN_ROAMINGPROFILE", "USERNAME",
];
private const string SessionEnvironmentKey = @"SYSTEM\CurrentControlSet\Control\Session Manager\Environment";
/// <summary>Replaces the contents of <paramref name="environment"/> with the sanitized set.</summary>
public static void Apply(IDictionary<string, string?> environment)
{
ArgumentNullException.ThrowIfNull(environment);
var kept = new Dictionary<string, string?>(StringComparer.OrdinalIgnoreCase);
foreach (var name in PassThrough)
{
var match = environment.FirstOrDefault(pair => string.Equals(pair.Key, name, StringComparison.OrdinalIgnoreCase));
if (match.Key is not null && !string.IsNullOrEmpty(match.Value))
{
kept[name] = match.Value;
}
}
environment.Clear();
foreach (var (name, value) in kept)
{
environment[name] = value;
}
foreach (var (name, value) in TrustedValues())
{
environment[name] = value;
}
}
/// <summary>System variables with values from the kernel, known folders and HKLM.</summary>
internal static IReadOnlyDictionary<string, string> TrustedValues()
{
var system32 = SystemPaths.System32;
var values = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase)
{
["SystemRoot"] = SystemPaths.WindowsDirectory,
["windir"] = SystemPaths.WindowsDirectory,
["SystemDrive"] = SystemPaths.SystemDrive,
["ComSpec"] = Path.Combine(system32, "cmd.exe"),
["USERPROFILE"] = SystemPaths.UserProfile,
["ProgramData"] = SystemPaths.ProgramData,
["ALLUSERSPROFILE"] = SystemPaths.ProgramData,
["PUBLIC"] = SystemPaths.Public,
["ProgramFiles"] = SystemPaths.ProgramFiles,
["ProgramW6432"] = SystemPaths.ProgramFiles,
["ProgramFiles(x86)"] = SystemPaths.ProgramFilesX86,
["CommonProgramFiles"] = SystemPaths.CommonProgramFiles,
["CommonProgramW6432"] = SystemPaths.CommonProgramFiles,
["CommonProgramFiles(x86)"] = SystemPaths.CommonProgramFilesX86,
// Only $PSHOME\Modules: Windows PowerShell 5.1 re-inserts the per-user module folder when
// this variable is missing or equals the machine value; to a narrower one it only adds the
// admin-only Program Files module folder (built from the trusted ProgramFiles value above).
["PSModulePath"] = Path.Combine(system32, "WindowsPowerShell", "v1.0", "Modules"),
["Path"] = MachinePath(),
["PATHEXT"] = SystemPaths.ReadMachineValue(SessionEnvironmentKey, "PATHEXT") ?? ".COM;.EXE;.BAT;.CMD;.VBS;.JS;.WSF;.WSH;.MSC",
};
return values;
}
/// <summary>The machine PATH from HKLM (no per-user directories), expanded with trusted values only.</summary>
private static string MachinePath()
{
var fallback = string.Join(';', SystemPaths.System32, SystemPaths.WindowsDirectory, Path.Combine(SystemPaths.System32, "Wbem"), Path.Combine(SystemPaths.System32, "WindowsPowerShell", "v1.0"));
if (SystemPaths.ReadMachineRawValue(SessionEnvironmentKey, "Path") is not { } raw)
{
return fallback;
}
var entries = raw
.Split(';', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries)
.Select(SystemPaths.ExpandTrusted)
.Where(entry => entry is not null && Path.IsPathFullyQualified(entry))
.Cast<string>()
.ToList();
return entries.Count == 0 ? fallback : string.Join(';', entries);
}
}
@@ -15,6 +15,9 @@ internal enum ElevationMessageKind
{
Output,
Result,
/// <summary>A diagnostic for the UI's log (the elevated side writes no files of its own).</summary>
Log,
}
/// <summary>A request from the UI. Only a <see cref="CommandId"/> is ever sent — never a command line.</summary>
@@ -25,7 +28,7 @@ internal sealed record ElevationRequest
public string? CommandId { get; init; }
}
/// <summary>A streamed output line or the final result.</summary>
/// <summary>A streamed output line, a log line, or the final result.</summary>
internal sealed record ElevationMessage
{
public ElevationMessageKind Kind { get; init; }
@@ -47,6 +50,9 @@ internal sealed record ElevationMessage
public static ElevationMessage Output(string text, bool isError)
=> new() { Kind = ElevationMessageKind.Output, Text = text, IsError = isError };
public static ElevationMessage LogLine(string text, bool isError)
=> new() { Kind = ElevationMessageKind.Log, Text = text, IsError = isError };
public static ElevationMessage FromResult(ExecutionResult result)
=> new()
{
@@ -27,6 +27,12 @@ internal sealed class ElevationServer
CancellationTokenSource? runCts = null;
var runTask = Task.CompletedTask;
// The elevated side has no log file; surface catalog problems in the UI's log instead.
foreach (var error in _catalog.ValidationErrors)
{
await channel.WriteAsync(ElevationMessage.LogLine($"Catalog: {error}", isError: true), ElevationJsonContext.Default.ElevationMessage, cancellationToken);
}
try
{
while (true)
@@ -40,7 +46,11 @@ internal sealed class ElevationServer
switch (request.Kind)
{
case ElevationRequestKind.Run:
runCts?.Cancel();
if (runCts is not null)
{
await runCts.CancelAsync();
}
await runTask;
runCts?.Dispose();
runCts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
@@ -48,7 +58,11 @@ internal sealed class ElevationServer
break;
case ElevationRequestKind.Cancel:
runCts?.Cancel();
if (runCts is not null)
{
await runCts.CancelAsync();
}
break;
default:
@@ -58,7 +72,11 @@ internal sealed class ElevationServer
}
finally
{
runCts?.Cancel();
if (runCts is not null)
{
await runCts.CancelAsync();
}
await runTask;
runCts?.Dispose();
}
@@ -0,0 +1,48 @@
using System.ComponentModel;
using System.Diagnostics;
using System.IO.Pipes;
using Windows.Win32;
namespace CommandForge.Infrastructure.Elevation;
/// <summary>
/// Checks who is on the other end of the elevation pipe. The pipe's ACL admits any process of the
/// same user, so both sides also confirm the peer's identity: the UI only talks to the Elevator it
/// launched, and the Elevator only serves CommandForge.Wpf.exe from its own install folder.
/// </summary>
internal static class PeerVerifier
{
/// <summary>File name of the UI executable the Elevator expects as its pipe server.</summary>
public const string UiExecutableName = "CommandForge.Wpf.exe";
/// <summary>UI side: true when the connected client is the process with <paramref name="expectedProcessId"/>.</summary>
public static bool IsExpectedClient(NamedPipeServerStream pipe, int expectedProcessId)
{
ArgumentNullException.ThrowIfNull(pipe);
return PInvoke.GetNamedPipeClientProcessId(pipe.SafePipeHandle, out var clientId)
&& clientId == (uint)expectedProcessId;
}
/// <summary>Elevator side: true when the pipe server is the UI executable next to this process.</summary>
public static bool IsExpectedServer(NamedPipeClientStream pipe)
{
ArgumentNullException.ThrowIfNull(pipe);
return PInvoke.GetNamedPipeServerProcessId(pipe.SafePipeHandle, out var serverId)
&& IsImage(serverId, Path.Combine(AppContext.BaseDirectory, UiExecutableName));
}
private static bool IsImage(uint processId, string expectedPath)
{
try
{
using var process = Process.GetProcessById((int)processId);
var image = process.MainModule?.FileName;
return image is not null
&& string.Equals(Path.GetFullPath(image), Path.GetFullPath(expectedPath), StringComparison.OrdinalIgnoreCase);
}
catch (Exception ex) when (ex is ArgumentException or InvalidOperationException or Win32Exception)
{
return false;
}
}
}
@@ -0,0 +1,25 @@
using System.Text;
using Windows.Win32;
namespace CommandForge.Infrastructure.Execution;
/// <summary>The code page native console tools use for redirected output.</summary>
internal static class ConsoleEncodings
{
/// <summary>The OEM code page (437 on US English, 1258 on Vietnamese, 932 on Japanese, 936 on Simplified Chinese…).</summary>
public static Encoding Oem { get; } = CreateOem();
private static Encoding CreateOem()
{
// .NET only ships UTF/ASCII/Latin-1 by default; the legacy code pages come from this provider.
Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
try
{
return Encoding.GetEncoding((int)PInvoke.GetOEMCP());
}
catch (Exception ex) when (ex is ArgumentException or NotSupportedException)
{
return Encoding.Latin1;
}
}
}
@@ -0,0 +1,56 @@
namespace CommandForge.Infrastructure.Execution;
/// <summary>
/// Turns a catalog executable name ("dism", "powershell", "services.msc") into an absolute path in
/// the Windows system directories. CreateProcess otherwise searches the application's own folder
/// first — for a per-user install that folder is writable by the user, so a planted "reg.exe" next
/// to the (elevated) Elevator would run with administrator rights.
/// </summary>
internal static class ExecutableResolver
{
private static readonly string[] ImplicitExtensions = [".exe", ".com", ".msc", ".cpl"];
/// <summary>Returns the absolute path for <paramref name="executable"/>, or the input unchanged when it can't be resolved.</summary>
public static string Resolve(string executable)
{
if (string.IsNullOrWhiteSpace(executable) || Path.IsPathRooted(executable)
|| executable.IndexOfAny([Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar]) >= 0)
{
return executable;
}
if (IsName(executable, "powershell"))
{
return Path.Combine(SystemPaths.System32, "WindowsPowerShell", "v1.0", "powershell.exe");
}
if (IsName(executable, "winget"))
{
// winget is an App Execution Alias in the user's WindowsApps folder, not a system binary.
var alias = Path.Combine(SystemPaths.LocalAppData, "Microsoft", "WindowsApps", "winget.exe");
return File.Exists(alias) ? alias : executable;
}
var candidates = Path.HasExtension(executable)
? [executable]
: ImplicitExtensions.Select(extension => executable + extension).ToArray();
foreach (var directory in new[] { SystemPaths.System32, SystemPaths.WindowsDirectory })
{
foreach (var candidate in candidates)
{
var path = Path.Combine(directory, candidate);
if (File.Exists(path))
{
return path;
}
}
}
return executable;
}
private static bool IsName(string executable, string name)
=> string.Equals(executable, name, StringComparison.OrdinalIgnoreCase)
|| string.Equals(executable, name + ".exe", StringComparison.OrdinalIgnoreCase);
}
@@ -0,0 +1,165 @@
using System.Text;
namespace CommandForge.Infrastructure.Execution;
/// <summary>
/// Splits a child process's raw stdout/stderr bytes into text lines. Windows tools disagree on the
/// encoding of redirected output: most write the console's OEM code page (localized text on
/// Vietnamese/Japanese/Chinese Windows), newer tools write UTF-8, and sfc/wsl write UTF-16LE. So the
/// stream is sniffed once for UTF-16LE, and otherwise every line is decoded as strict UTF-8 with an
/// OEM-code-page fallback. Line breaks are \n, \r\n or a lone \r (progress updates).
/// </summary>
internal sealed class OutputDecoder
{
private static readonly UTF8Encoding StrictUtf8 = new(encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: true);
private readonly Encoding _fallback;
private readonly List<byte> _pending = [];
private bool? _utf16;
private bool _bomChecked;
public OutputDecoder(Encoding fallback)
{
ArgumentNullException.ThrowIfNull(fallback);
_fallback = fallback;
}
/// <summary>Appends <paramref name="chunk"/> and adds every completed line to <paramref name="lines"/>.</summary>
public void Push(ReadOnlySpan<byte> chunk, List<string> lines)
{
ArgumentNullException.ThrowIfNull(lines);
foreach (var b in chunk)
{
_pending.Add(b);
}
_utf16 ??= DetectUtf16(_pending);
if (_utf16 is null)
{
return; // not enough bytes yet to tell UTF-16LE from a byte encoding
}
if (_utf16 == true && !_bomChecked && _pending.Count >= 2)
{
if (_pending[0] == 0xFF && _pending[1] == 0xFE)
{
_pending.RemoveRange(0, 2);
}
_bomChecked = true;
}
ExtractLines(lines, endOfStream: false);
}
/// <summary>Returns the trailing text after the last line break (call once at end of stream).</summary>
public string? Flush()
{
_utf16 ??= false;
var lines = new List<string>();
ExtractLines(lines, endOfStream: true);
return lines.Count == 0 ? null : string.Join(Environment.NewLine, lines);
}
private void ExtractLines(List<string> lines, bool endOfStream)
{
var unit = _utf16 == true ? 2 : 1;
var start = 0;
var i = 0;
while (i + unit <= _pending.Count)
{
var code = CodeAt(i, unit);
if (code == '\n')
{
lines.Add(Decode(start, i));
i += unit;
start = i;
}
else if (code == '\r')
{
var next = i + unit;
if (next + unit > _pending.Count && !endOfStream)
{
break; // can't tell yet whether a \n follows
}
lines.Add(Decode(start, i));
var nextCode = next + unit <= _pending.Count ? CodeAt(next, unit) : -1;
i = nextCode == '\n' ? next + unit : next;
start = i;
}
else
{
i += unit;
}
}
if (endOfStream && start < _pending.Count)
{
lines.Add(Decode(start, _pending.Count));
start = _pending.Count;
}
_pending.RemoveRange(0, start);
}
/// <summary>The code unit at <paramref name="index"/>: one byte, or a little-endian UTF-16 unit.</summary>
private int CodeAt(int index, int unit)
=> unit == 2 ? _pending[index] | (_pending[index + 1] << 8) : _pending[index];
private string Decode(int start, int end)
{
if (end <= start)
{
return string.Empty;
}
var bytes = _pending.GetRange(start, end - start).ToArray();
if (_utf16 == true)
{
return Encoding.Unicode.GetString(bytes);
}
try
{
return StrictUtf8.GetString(bytes);
}
catch (DecoderFallbackException)
{
return _fallback.GetString(bytes);
}
}
/// <summary>UTF-16LE when a BOM is present or most odd bytes of plain-ASCII-range text are zero.</summary>
private static bool? DetectUtf16(List<byte> data)
{
if (data.Count >= 2 && data[0] == 0xFF && data[1] == 0xFE)
{
return true;
}
if (data.Count < 4)
{
return null; // decide once there is enough to look at
}
var sample = Math.Min(data.Count, 512) & ~1;
var zeroOdd = 0;
var zeroEven = 0;
for (var i = 0; i < sample; i += 2)
{
if (data[i] == 0)
{
zeroEven++;
}
if (data[i + 1] == 0)
{
zeroOdd++;
}
}
var pairs = sample / 2;
return zeroOdd * 2 >= pairs && zeroEven * 4 < pairs;
}
}
@@ -1,7 +1,9 @@
using System.ComponentModel;
using System.Diagnostics;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Channels;
using CommandForge.Application;
using CommandForge.Application.Ports;
using CommandForge.Domain;
@@ -14,36 +16,54 @@ namespace CommandForge.Infrastructure.Execution;
/// </summary>
internal sealed class ProcessCommandExecutor : ICommandExecutor
{
private readonly IProcessRunner _runner;
// Only the tail of the output is kept for regex restart detection.
private const int MaxCapturedChars = 256 * 1024;
public ProcessCommandExecutor(IProcessRunner runner) => _runner = runner;
// Catalog patterns are vetted, but output size is unbounded — cap the match time anyway.
private static readonly TimeSpan RegexTimeout = TimeSpan.FromSeconds(2);
private readonly IProcessRunner _runner;
private readonly IReadOnlyDictionary<string, string> _tokens;
public ProcessCommandExecutor(IProcessRunner runner)
: this(runner, SystemPathTokens.Values)
{
}
internal ProcessCommandExecutor(IProcessRunner runner, IReadOnlyDictionary<string, string> tokens)
{
_runner = runner;
_tokens = tokens;
}
/// <inheritdoc />
public async Task<ExecutionResult> ExecuteAsync(
CommandDefinition command,
ChannelWriter<OutputLine> output,
CancellationToken cancellationToken)
CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(command);
ArgumentNullException.ThrowIfNull(output);
var stopwatch = Stopwatch.StartNew();
var arguments = ArgumentTokens.Expand(command.ArgsTemplate, _tokens);
if (command.ExecutionMode == ExecutionMode.Launch)
{
return Launch(command, output, stopwatch);
return Launch(command, arguments, output, stopwatch);
}
var capturedLines = new List<string>();
// Keep (a bounded tail of) the text only when a restart regex needs to inspect it.
var captured = command.Restart == RestartPolicy.FromOutputRegex ? new StringBuilder() : null;
// Internal pipe: runner (background threads) -> here. We tee each line to the caller's
// channel (for the UI) while capturing the full text for regex restart detection.
// Internal pipe: runner (background threads) -> here. Each line is teed to the caller's
// channel (for the UI) and, when needed, into the capture buffer.
var inner = Channel.CreateUnbounded<OutputLine>(new UnboundedChannelOptions { SingleReader = true });
var runTask = _runner.RunAsync(command.Executable, command.ArgsTemplate, inner.Writer, cancellationToken);
var runTask = _runner.RunAsync(command.Executable, arguments, inner.Writer, cancellationToken);
await foreach (var line in inner.Reader.ReadAllAsync(CancellationToken.None))
{
capturedLines.Add(line.Text);
Capture(captured, line.Text);
await output.WriteAsync(line, CancellationToken.None);
}
@@ -60,7 +80,6 @@ internal sealed class ProcessCommandExecutor : ICommandExecutor
catch (Exception ex) when (ex is Win32Exception or InvalidOperationException)
{
var error = $"Failed to start '{command.Executable}': {ex.Message}";
capturedLines.Add(error);
await output.WriteAsync(new OutputLine(error, IsError: true), CancellationToken.None);
}
finally
@@ -69,27 +88,24 @@ internal sealed class ProcessCommandExecutor : ICommandExecutor
}
stopwatch.Stop();
var requiresRestart = !cancelled && DetectRestart(command, exitCode, string.Join('\n', capturedLines));
return new ExecutionResult
{
ExitCode = exitCode,
Success = !cancelled && (exitCode == 0 || exitCode == ExecutionResult.RebootRequiredExitCode),
Duration = stopwatch.Elapsed,
RequiresRestart = requiresRestart,
RequiresRestart = !cancelled && DetectRestart(command, exitCode, captured),
Cancelled = cancelled,
OutputLines = capturedLines,
};
}
private ExecutionResult Launch(CommandDefinition command, ChannelWriter<OutputLine> output, Stopwatch stopwatch)
private ExecutionResult Launch(CommandDefinition command, string arguments, ChannelWriter<OutputLine> output, Stopwatch stopwatch)
{
string message;
bool success;
try
{
_runner.Launch(command.Executable, command.ArgsTemplate);
message = $"Launched: {command.Executable} {command.ArgsTemplate}".Trim();
_runner.Launch(command.Executable, arguments);
message = $"Launched: {command.Executable} {arguments}".Trim();
success = true;
}
catch (Exception ex) when (ex is Win32Exception or InvalidOperationException)
@@ -107,18 +123,41 @@ internal sealed class ProcessCommandExecutor : ICommandExecutor
ExitCode = success ? 0 : -1,
Success = success,
Duration = stopwatch.Elapsed,
RequiresRestart = false,
// A launched tool runs on its own; only an unconditional policy can be honoured.
RequiresRestart = success && command.Restart == RestartPolicy.Always,
Cancelled = false,
OutputLines = [message],
};
}
private static bool DetectRestart(CommandDefinition command, int exitCode, string output)
=> command.Restart switch
private static void Capture(StringBuilder? captured, string line)
{
if (captured is null)
{
return;
}
captured.Append(line).Append('\n');
if (captured.Length > MaxCapturedChars)
{
captured.Remove(0, captured.Length - MaxCapturedChars);
}
}
private static bool DetectRestart(CommandDefinition command, int exitCode, StringBuilder? captured)
{
// 3010 is Windows' own "succeeded, restart required" signal, whatever the catalog policy says.
if (exitCode == ExecutionResult.RebootRequiredExitCode)
{
return true;
}
return command.Restart switch
{
RestartPolicy.Always => true,
RestartPolicy.FromExitCode => exitCode == ExecutionResult.RebootRequiredExitCode,
RestartPolicy.FromOutputRegex => command.RestartRegex is { } pattern && Regex.IsMatch(output, pattern),
RestartPolicy.FromOutputRegex => command.RestartRegex is { } pattern
&& captured is not null
&& Regex.IsMatch(captured.ToString(), pattern, RegexOptions.None, RegexTimeout),
_ => false,
};
}
}
@@ -0,0 +1,65 @@
using System.Diagnostics;
using System.Runtime.InteropServices;
using Microsoft.Win32.SafeHandles;
using Windows.Win32;
using Windows.Win32.System.JobObjects;
namespace CommandForge.Infrastructure.Execution;
/// <summary>
/// A process-wide job object with "kill on close": every captured command process (and anything it
/// starts) is placed in it, so when CommandForge — or the Elevator — exits or crashes, Windows ends
/// those processes instead of leaving a half-finished DISM/winget run behind. GUI targets started in
/// Launch mode are deliberately not added; they belong to the user.
/// </summary>
internal sealed class ProcessJob : IDisposable
{
private static readonly Lazy<ProcessJob> SharedInstance = new(() => new ProcessJob());
private readonly SafeFileHandle? _job;
private ProcessJob()
{
try
{
_job = PInvoke.CreateJobObject(lpJobAttributes: null, lpName: null);
var limits = new JOBOBJECT_EXTENDED_LIMIT_INFORMATION();
limits.BasicLimitInformation.LimitFlags = JOB_OBJECT_LIMIT.JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE;
var bytes = MemoryMarshal.AsBytes(new ReadOnlySpan<JOBOBJECT_EXTENDED_LIMIT_INFORMATION>(in limits));
if (_job.IsInvalid || !PInvoke.SetInformationJobObject(_job, JOBOBJECTINFOCLASS.JobObjectExtendedLimitInformation, bytes))
{
_job.Dispose();
_job = null;
}
}
catch (Exception ex) when (ex is EntryPointNotFoundException or DllNotFoundException)
{
_job = null;
}
}
/// <summary>The shared job for this process.</summary>
public static ProcessJob Shared => SharedInstance.Value;
/// <summary>Adds <paramref name="process"/> to the job. Best effort: a failure only loses the clean-up guarantee.</summary>
public bool TryAdd(Process process)
{
ArgumentNullException.ThrowIfNull(process);
if (_job is null)
{
return false;
}
try
{
return PInvoke.AssignProcessToJobObject(_job, process.SafeHandle);
}
catch (InvalidOperationException)
{
return false; // the process already exited
}
}
/// <inheritdoc />
public void Dispose() => _job?.Dispose();
}
@@ -0,0 +1,15 @@
using CommandForge.Application;
namespace CommandForge.Infrastructure.Execution;
/// <summary>Values for <see cref="ArgumentTokens"/>, taken from <see cref="SystemPaths"/> (trusted sources only).</summary>
public static class SystemPathTokens
{
/// <summary>Token → value map used by the executor and by the command preview.</summary>
public static IReadOnlyDictionary<string, string> Values { get; } = new Dictionary<string, string>(StringComparer.Ordinal)
{
[ArgumentTokens.SystemDrive] = SystemPaths.SystemDrive,
[ArgumentTokens.SystemRoot] = SystemPaths.WindowsDirectory,
[ArgumentTokens.UserProfile] = SystemPaths.UserProfile,
};
}
Loaded 100 of 304 files, more files were not shown because too many files have changed in this diff. Show more