Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
25 commits
Select commit Hold shift + click to select a range
6f2ba48
feat(extension): introduce Plugin / Hook framework with command pruning
sang-neo03 May 13, 2026
f34d051
fix(pruning): deny stub must override Args + PersistentPreRunE
sang-neo03 May 13, 2026
b3a6a35
Merge branch 'main' into feat/extension-platform
sang-neo03 May 13, 2026
2bedf8c
fix(config): policy subcommand bypasses parent's credential check
sang-neo03 May 13, 2026
b0e2d4d
feat(shortcuts): tag service groups with cmdmeta.Domain
sang-neo03 May 13, 2026
203ef32
feat(diagnostic): add unconditionally allowed command paths for intro…
sang-neo03 May 14, 2026
c046ed4
feat(plugins): add diagnostic command to inspect installed plugins an…
sang-neo03 May 14, 2026
aa9760e
Merge branch 'main' into feat/extension-platform
sang-neo03 May 15, 2026
9429c52
fix(cli): surface unknown_subcommand error instead of silent help fal…
sang-neo03 May 15, 2026
adfe1f8
refactor(envelope): rename error.type pruning/strict_mode to command_…
sang-neo03 May 15, 2026
bb20e40
feat(platform): fail closed on unannotated/invalid risk when a Rule i…
sang-neo03 May 15, 2026
27efb9d
chore(config): hide diagnostic policy/plugins commands from --help
sang-neo03 May 15, 2026
7d28188
Merge branch 'main' into feat/extension-platform
sang-neo03 May 15, 2026
cbfa752
style: gofmt
sang-neo03 May 15, 2026
a2dff61
Merge branch 'main' into feat/extension-platform
sang-neo03 May 15, 2026
2a6f0f4
fix(platform): nil Selector honours None contract; reject multi-doc p…
sang-neo03 May 16, 2026
06b06ed
chore: go mod tidy
sang-neo03 May 16, 2026
461e3c6
feat(extension/platform): plugin SDK with policy engine, hooks, and B…
liangshuo-1 May 16, 2026
4ff5ad2
feat(extension/platform): plugin SDK with policy engine, hooks, and B…
liangshuo-1 May 16, 2026
b78df3d
Merge remote-tracking branch 'origin/feat/extension-platform' into fe…
sang-neo03 May 16, 2026
aacb5d7
refactor(policy): remove validate command and update diagnostics
sang-neo03 May 16, 2026
0efee93
fix(extension/platform): address PR review must-fix items
sang-neo03 May 16, 2026
baa8878
Merge branch 'main' into feat/extension-platform
sang-neo03 May 16, 2026
eba0d75
fix(extension/platform): address CodeRabbit review comments + CI gofmt
sang-neo03 May 16, 2026
1f9f75a
fix(cmdpolicy): replace filepath.Abs with filepath.Clean for lint policy
sang-neo03 May 16, 2026
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 6 additions & 6 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ jobs:
- name: Build
run: go build ./...
- name: Vet
run: go vet ./...
run: go vet -tags testing ./...
- name: Check formatting
run: |
unformatted=$(gofmt -l .)
Expand Down Expand Up @@ -63,7 +63,7 @@ jobs:
- name: Fetch meta data
run: python3 scripts/fetch_meta.py
- name: Run tests
run: go test -v -race -count=1 -timeout=5m ./cmd/... ./internal/... ./shortcuts/...
run: go test -tags testing -v -race -count=1 -timeout=5m ./cmd/... ./internal/... ./shortcuts/... ./extension/...

lint:
needs: fast-gate
Expand All @@ -81,7 +81,7 @@ jobs:
- name: Fetch meta data
run: python3 scripts/fetch_meta.py
- name: Run golangci-lint
run: go run github.com/golangci/golangci-lint/v2/cmd/golangci-lint@v2.1.6 run --new-from-rev=origin/main
run: go run github.com/golangci/golangci-lint/v2/cmd/golangci-lint@v2.1.6 run --build-tags=testing --new-from-rev=origin/main

coverage:
needs: fast-gate
Expand All @@ -99,7 +99,7 @@ jobs:
- name: Run tests with coverage
run: |
packages=$(go list ./... | grep -v '^github.com/larksuite/cli/tests/cli_e2e$' | grep -v '^github.com/larksuite/cli/tests/cli_e2e/')
go test -race -coverprofile=coverage.txt -covermode=atomic $packages
go test -tags testing -race -coverprofile=coverage.txt -covermode=atomic $packages
- name: Upload coverage to Codecov
uses: codecov/codecov-action@3f20e214133d0983f9a10f3d63b0faf9241a3daa # v6
with:
Expand Down Expand Up @@ -153,14 +153,14 @@ jobs:
run: |
# Analyze current HEAD (strip line:col for stable diff across line shifts)
# Filter "go: downloading ..." lines to avoid false diffs from module cache state
go run golang.org/x/tools/cmd/deadcode@v0.31.0 -test ./... 2>&1 | \
go run golang.org/x/tools/cmd/deadcode@v0.31.0 -tags=testing -test ./... 2>&1 | \
grep -v '^go: ' | \
sed 's/:[0-9][0-9]*:[0-9][0-9]*:/:/' | sort > /tmp/dc-head.txt

# Analyze base branch via worktree
git worktree add -q /tmp/dc-base "origin/${{ github.base_ref }}"
(cd /tmp/dc-base && python3 scripts/fetch_meta.py && \
go run golang.org/x/tools/cmd/deadcode@v0.31.0 -test ./... 2>&1 | \
go run golang.org/x/tools/cmd/deadcode@v0.31.0 -tags=testing -test ./... 2>&1 | \
grep -v '^go: ' | \
sed 's/:[0-9][0-9]*:[0-9][0-9]*:/:/' | sort > /tmp/dc-base.txt) || {
echo "::warning::Failed to analyze base branch — skipping incremental dead code check"
Expand Down
30 changes: 26 additions & 4 deletions Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ DATE := $(shell date +%Y-%m-%d)
LDFLAGS := -s -w -X $(MODULE)/internal/build.Version=$(VERSION) -X $(MODULE)/internal/build.Date=$(DATE)
PREFIX ?= /usr/local

.PHONY: all build vet test unit-test integration-test install uninstall clean fetch_meta gitleaks
.PHONY: all build vet fmt-check test unit-test integration-test examples-build install uninstall clean fetch_meta gitleaks

all: test

Expand All @@ -19,15 +19,37 @@ build: fetch_meta
go build -trimpath -ldflags "$(LDFLAGS)" -o $(BINARY) .

vet: fetch_meta
go vet ./...
go vet -tags testing ./...

# fmt-check fails when any file would be reformatted by gofmt. Keep this
# in sync with the fast-gate "Check formatting" step in CI.
fmt-check:
@unformatted=$$(gofmt -l . | grep -v '^\.claude/' || true); \
if [ -n "$$unformatted" ]; then \
echo "Unformatted Go files:"; \
echo "$$unformatted"; \
echo "Run 'gofmt -w .' and commit."; \
exit 1; \
fi

# unit-test passes -tags testing because public-SDK packages gate test-only
# helpers (e.g. platform.ResetForTesting) behind //go:build testing. The
# ./extension/... package list keeps the public plugin SDK in the default
# test matrix.
unit-test: fetch_meta
go test -race -gcflags="all=-N -l" -count=1 ./cmd/... ./internal/... ./shortcuts/...
go test -tags testing -race -gcflags="all=-N -l" -count=1 \
./cmd/... ./internal/... ./shortcuts/... ./extension/...

# examples-build keeps the shipped plugin-SDK examples compilable. If this
# breaks, the plugin author guide's "go build ./..." path is broken.
examples-build:
go build ./extension/platform/examples/audit-observer
go build ./extension/platform/examples/readonly-policy

integration-test: build
go test -v -count=1 ./tests/...

test: vet unit-test integration-test
test: vet fmt-check unit-test examples-build integration-test

install: build
install -d $(PREFIX)/bin
Expand Down
2 changes: 1 addition & 1 deletion cmd/auth/login.go
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ For AI agents: this command blocks until the user completes authorization in the
browser. Run it in the background and retrieve the verification URL from its output.`,
RunE: func(cmd *cobra.Command, args []string) error {
if mode := f.ResolveStrictMode(cmd.Context()); mode == core.StrictModeBot {
return output.ErrWithHint(output.ExitValidation, "strict_mode",
return output.ErrWithHint(output.ExitValidation, "command_denied",
fmt.Sprintf("strict mode is %q, user login is disabled in this profile", mode),
"if the user explicitly wants to switch to user identity, see `lark-cli config strict-mode --help` (confirm with the user before switching; switching does NOT require re-bind)")
}
Expand Down
80 changes: 76 additions & 4 deletions cmd/build.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,9 @@
cmdupdate "github.com/larksuite/cli/cmd/update"
_ "github.com/larksuite/cli/events"
"github.com/larksuite/cli/internal/build"
"github.com/larksuite/cli/internal/cmdpolicy"
"github.com/larksuite/cli/internal/cmdutil"
"github.com/larksuite/cli/internal/hook"
"github.com/larksuite/cli/internal/keychain"
"github.com/larksuite/cli/shortcuts"
"github.com/spf13/cobra"
Expand Down Expand Up @@ -60,17 +62,22 @@
}

// Build constructs the full command tree without executing.
// Returns only the cobra.Command; Factory is internal.
// Returns only the cobra.Command; Factory and hook Registry are internal.
// Use Execute for the standard production entry point.
func Build(ctx context.Context, inv cmdutil.InvocationContext, opts ...BuildOption) *cobra.Command {
_, rootCmd := buildInternal(ctx, inv, opts...)
_, rootCmd, _ := buildInternal(ctx, inv, opts...)
return rootCmd
}

// buildInternal is a pure assembly function: it wires the command tree from
// inv and BuildOptions alone. Any state-dependent decision (disk, network,
// env) belongs in the caller and must be threaded in via BuildOption.
func buildInternal(ctx context.Context, inv cmdutil.InvocationContext, opts ...BuildOption) (*cmdutil.Factory, *cobra.Command) {
//
// Returns (factory, rootCmd, registry). The registry is nil when plugin
// install failed (FailClosed guard installed) or when no plugin produced
// hooks; callers that wire Shutdown emit must nil-check before calling
// hook.Emit.
func buildInternal(ctx context.Context, inv cmdutil.InvocationContext, opts ...BuildOption) (*cmdutil.Factory, *cobra.Command, *hook.Registry) {
// cfg.globals.Profile is left zero here; it's bound to the --profile
// flag in RegisterGlobalFlags and filled by cobra's parse step.
cfg := &buildConfig{}
Expand Down Expand Up @@ -124,10 +131,75 @@
service.RegisterServiceCommandsWithContext(ctx, rootCmd, f)
shortcuts.RegisterShortcutsWithContext(ctx, rootCmd, f)

installUnknownSubcommandGuard(rootCmd)

// Prune commands incompatible with strict mode.
if mode := f.ResolveStrictMode(ctx); mode.IsActive() {
pruneForStrictMode(rootCmd, mode)
}

return f, rootCmd
// Run the platform host: install registered plugins, collecting
// their Restrict() contributions and their hooks. FailClosed
// failures (and untrusted-config failures like restricts_mismatch)
// are abort-worthy: InstallAll returns an error in those cases.
// We honour that by installing a PersistentPreRunE that emits
// the structured envelope at command-dispatch time -- buildInternal
// itself cannot return an error without breaking its assembly
// contract, but cobra runs PersistentPreRunE before any RunE so
// the user sees the error on their very next invocation.
installResult, installErr := installPluginsAndHooks(cfg.streams.ErrOut)
if installErr != nil {
installPluginInstallErrorGuard(rootCmd, installErr)
// Stop wiring more state from a failed install -- the rest of
// the function would only matter if the CLI is allowed to
// proceed normally, which it isn't.
return f, rootCmd, nil
}
var pluginRules []cmdpolicy.PluginRule
var registry *hook.Registry
if installResult != nil {
pluginRules = installResult.PluginRules
registry = installResult.Registry
}

// Apply user-layer command pruning: yaml + Plugin.Restrict.
//
// **Error policy splits by source**:
// - Plugin path (any pluginRules contributed): a validation or
// conflict error is a HARD failure -- the plugin author asked
// for a security policy, silently dropping it would leave the
// CLI more permissive than intended. Abort via the conflict
// guard so every command surfaces the structured envelope.
// - yaml-only path: stays fail-OPEN with a warning. A user typo
// in policy.yml must not lock them out of every command.
if err := applyUserPolicyPruning(rootCmd, pluginRules); err != nil {
if len(pluginRules) > 0 {
installPluginConflictGuard(rootCmd, err)
return f, rootCmd, nil
}
warnPolicyError(cfg.streams.ErrOut, err)

Check warning on line 180 in cmd/build.go

View check run for this annotation

Codecov / codecov/patch

cmd/build.go#L180

Added line #L180 was not covered by tests
Comment thread
sang-neo03 marked this conversation as resolved.
}

// Install hooks onto the (now-pruned) command tree and emit the
// Startup lifecycle event so Plugin.On(Startup) handlers can run.
//
// Startup handler error or panic is a HARD failure: a plugin's
// Startup logic is part of its install contract, and silently
// continuing would mean the plugin's invariants do not hold while
// the rest of its hooks (Wrap / Observe) still fire. Install the
// plugin_lifecycle guard and short-circuit so every subsequent
// dispatch surfaces the envelope.
if registry != nil {
if err := wireHooks(ctx, rootCmd, registry); err != nil {
installPluginLifecycleErrorGuard(rootCmd, err)
return f, rootCmd, nil
}
}

// Snapshot the plugin inventory so `config plugins show` can answer
// "what plugins / hooks / rules are currently in effect" without
// re-calling plugin methods at display time.
recordInventory(installResult)

return f, rootCmd, registry
}
7 changes: 7 additions & 0 deletions cmd/config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,11 @@ func NewCmdConfig(f *cmdutil.Factory) *cobra.Command {
cmd := &cobra.Command{
Use: "config",
Short: "Global CLI configuration management",
Long: `Global CLI configuration management.

Diagnostic (hidden) commands — runnable but omitted from --help:
lark-cli config policy show Inspect active user-layer policy
lark-cli config plugins show Inspect installed plugins and hooks`,
PersistentPreRunE: func(cmd *cobra.Command, args []string) error {
// Replicate rootCmd's PersistentPreRun behaviour: cobra stops at the first
// PersistentPreRun[E] found walking up the chain, so the root-level
Expand All @@ -31,6 +36,8 @@ func NewCmdConfig(f *cmdutil.Factory) *cobra.Command {
cmd.AddCommand(NewCmdConfigShow(f, nil))
cmd.AddCommand(NewCmdConfigDefaultAs(f))
cmd.AddCommand(NewCmdConfigStrictMode(f))
cmd.AddCommand(NewCmdConfigPolicy(f))
cmd.AddCommand(NewCmdConfigPlugins(f))
return cmd
}

Expand Down
99 changes: 99 additions & 0 deletions cmd/config/plugins.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,99 @@
// Copyright (c) 2026 Lark Technologies Pte. Ltd.
// SPDX-License-Identifier: MIT

package config

import (
"github.com/spf13/cobra"

"github.com/larksuite/cli/internal/cmdutil"
"github.com/larksuite/cli/internal/output"
internalplatform "github.com/larksuite/cli/internal/platform"
)

// NewCmdConfigPlugins exposes the plugin inventory diagnostic command.
//
// `config policy show` is intentionally focused on the user-layer Rule
// (Restrict). Plugins also contribute hooks (Observe / Wrap / Lifecycle)
// that are not policy gates but still mutate the CLI's runtime behaviour.
// This command surfaces both halves so an operator can answer "what is
// this binary doing differently from stock lark-cli?" in one place.
//
// Like config policy show, the dispatch path is exempt from policy
// enforcement (see internal/cmdpolicy/diagnostic.go) so it remains
// usable under any Rule.
func NewCmdConfigPlugins(f *cmdutil.Factory) *cobra.Command {
cmd := &cobra.Command{
Use: "plugins",
Hidden: true, // diagnostic-only; kept callable, omitted from --help so it stays out of AI-agent context
Short: "Inspect installed plugins and their hook contributions",
// Same leaf-level no-op as config policy: the parent `config`
// group's PersistentPreRunE requires builtin credential, but
// this is a read-only diagnostic that must work everywhere.
PersistentPreRunE: func(c *cobra.Command, _ []string) error {
c.SilenceUsage = true
return nil
},

Check warning on line 36 in cmd/config/plugins.go

View check run for this annotation

Codecov / codecov/patch

cmd/config/plugins.go#L34-L36

Added lines #L34 - L36 were not covered by tests
}
cmd.AddCommand(newCmdConfigPluginsShow(f))
return cmd
}

func newCmdConfigPluginsShow(f *cmdutil.Factory) *cobra.Command {
return &cobra.Command{
Use: "show",
Short: "List successfully installed plugins, their rules, and registered hooks",
Long: `Print every plugin that committed during bootstrap, including:

- name / version / capabilities (FailurePolicy, Restricts, RequiredCLIVersion)
- rule (when the plugin called r.Restrict)
- hooks: observers (Before / After), wrappers, lifecycle handlers

Hooks are attributed by their namespaced name -- the framework prepends
the plugin name as the prefix at registration time, so an entry
"secaudit.audit-pre" belongs to plugin "secaudit".`,
RunE: func(cmd *cobra.Command, args []string) error {
return runConfigPluginsShow(f)
},

Check warning on line 57 in cmd/config/plugins.go

View check run for this annotation

Codecov / codecov/patch

cmd/config/plugins.go#L56-L57

Added lines #L56 - L57 were not covered by tests
}
}

func runConfigPluginsShow(f *cmdutil.Factory) error {
inv := internalplatform.GetActiveInventory()
if inv == nil {

Check warning on line 63 in cmd/config/plugins.go

View check run for this annotation

Codecov / codecov/patch

cmd/config/plugins.go#L61-L63

Added lines #L61 - L63 were not covered by tests
// Always emit the same field set as the populated branch so
// AI agents and CI scripts don't have to branch on whether
// `total` is present. `note` makes the unusual state explicit
// for human readers.
output.PrintJson(f.IOStreams.Out, map[string]any{
"plugins": []any{},
"total": 0,
"note": "no inventory recorded; bootstrap did not finish",
})
Comment thread
coderabbitai[bot] marked this conversation as resolved.
return nil

Check warning on line 73 in cmd/config/plugins.go

View check run for this annotation

Codecov / codecov/patch

cmd/config/plugins.go#L68-L73

Added lines #L68 - L73 were not covered by tests
}

plugins := make([]map[string]any, 0, len(inv.Plugins))
for _, p := range inv.Plugins {
entry := map[string]any{
"name": p.Name,
"version": p.Version,
"capabilities": p.Capabilities,

Check warning on line 81 in cmd/config/plugins.go

View check run for this annotation

Codecov / codecov/patch

cmd/config/plugins.go#L76-L81

Added lines #L76 - L81 were not covered by tests
}
if p.Rule != nil {
entry["rule"] = p.Rule

Check warning on line 84 in cmd/config/plugins.go

View check run for this annotation

Codecov / codecov/patch

cmd/config/plugins.go#L83-L84

Added lines #L83 - L84 were not covered by tests
}
entry["hooks"] = map[string]any{
"observers": p.Observers,
"wrappers": p.Wrappers,
"lifecycle": p.Lifecycles,
"count": len(p.Observers) + len(p.Wrappers) + len(p.Lifecycles),

Check warning on line 90 in cmd/config/plugins.go

View check run for this annotation

Codecov / codecov/patch

cmd/config/plugins.go#L86-L90

Added lines #L86 - L90 were not covered by tests
}
plugins = append(plugins, entry)

Check warning on line 92 in cmd/config/plugins.go

View check run for this annotation

Codecov / codecov/patch

cmd/config/plugins.go#L92

Added line #L92 was not covered by tests
}
output.PrintJson(f.IOStreams.Out, map[string]any{
"plugins": plugins,
"total": len(plugins),
})
return nil

Check warning on line 98 in cmd/config/plugins.go

View check run for this annotation

Codecov / codecov/patch

cmd/config/plugins.go#L94-L98

Added lines #L94 - L98 were not covered by tests
}
Loading
Loading