feat(cli): add agent-first affordance — envelope, exit-10, --dry-run

Borrows the lark-cli agent-affordance model
(https://github.com/larksuite/cli/blob/main/AGENTS.md +
skills/lark-shared/SKILL.md) so weknora is designed to be agent-friendly:
error messages, output format, and flag design follow conventions agents
can rely on.

cli/AGENTS.md (operational reference for LLM agents invoking weknora):
  Public document covering envelope schema, exit-code protocol
  (0/1/2/10/130), stdout/stderr separation, and behavioral rules.
  Sensitive commands (\`context use\`, \`kb delete\`, \`doc delete\`, \`init\`)
  gain "AI agents:" paragraphs in their cobra Long descriptions so
  guidance shows in --help.

format.Envelope schema additions:
  Risk    per-operation classification (read / write / high-risk-write +
          action description), populated by write commands on both success
          and failure paths.
  Notice  system advisories (CLI update available, server-CLI version
          skew); type defined, emit sites land in v0.3.
  DryRun  marker for envelopes returned from --dry-run preview paths.

  RiskLevel constants realigned to lark's taxonomy: read / write /
  high-risk-write (was: read / mutating / destructive — not yet wired by
  any command).

  cmdutil.Error gains OperationRisk; PrintErrorEnvelope auto-attaches it
  to envelope.Risk so destructive failure paths surface uniformly.

Exit-10 confirmation protocol:
  New ErrorCode \`input.confirmation_required\` mapped to exit code 10 in
  cmdutil.ExitCode. ConfirmDestructive now returns this code (with
  OperationRisk attached) when stdout is non-TTY or --json was set, with
  -y/--yes absent. Previous behavior — silent proceed in non-TTY — was
  unsafe: scripts and agents could delete resources with no explicit
  approval. Three test cases re-pinned around the new contract.

  This is a wire-contract change for any caller who relied on silent
  proceed; v0.0/v0.1 had no destructive commands, so the blast radius is
  contained to v0.2 itself.

--dry-run global flag:
  cmd write paths (kb create/delete, doc upload/delete, api POST/PUT/PATCH/
  DELETE) check cmdutil.IsDryRun(cmd) and skip the SDK call, emitting an
  envelope with dry_run=true plus a Risk classification. Read commands
  ignore --dry-run by design (no side effect to preview). Human-mode
  prints \`[dry-run] would <action>\` to stdout.

Command discovery: agents introspect via the existing \`--help\` surface
(consistent with gh / kubectl / aws / gcloud / terraform — none of them
ship a CLI-tree self-description command). An earlier draft added a
\`weknora schema\` reflection command; dropped after a mainstream survey
found it has no stable analog (lark-cli's schema describes Lark API
methods, not its own CLI tree).

Tests: 27 cli packages pass at this commit. Added two new tests covering
envelope.risk and envelope._notice serialization.
This commit is contained in:
nullkey
2026-05-11 02:44:34 +08:00
committed by lyingbug
parent 9d2e740753
commit da9faa9e07
38 changed files with 634 additions and 104 deletions
+18 -2
View File
@@ -18,6 +18,7 @@ import (
type DeleteOptions struct {
Yes bool
JSONOut bool
DryRun bool
}
// DeleteService is the narrow SDK surface this command depends on.
@@ -41,13 +42,21 @@ func NewCmdDelete(f *cmdutil.Factory) *cobra.Command {
Short: "Delete a document from a knowledge base",
Long: `Permanently deletes one document. Prompts for confirmation by default
when stdout is a TTY and --json is not set; pass -y/--yes (global flag) to skip
the prompt (required in agent / CI / piped contexts).`,
the prompt (required in agent / CI / piped contexts).
AI agents: This is a high-risk write. Without -y/--yes the CLI exits 10 and
returns an envelope describing the missing confirmation. NEVER auto-pass -y
without the user's explicit go-ahead.`,
Example: ` weknora doc delete doc_abc # interactive confirm
weknora doc delete doc_abc -y # no prompt
weknora doc delete doc_abc -y --json # envelope output`,
Args: cobra.ExactArgs(1),
RunE: func(c *cobra.Command, args []string) error {
opts.Yes, _ = c.Flags().GetBool("yes")
opts.DryRun = cmdutil.IsDryRun(c)
if opts.DryRun {
return runDelete(c.Context(), opts, nil, f.Prompter(), args[0])
}
cli, err := f.Client()
if err != nil {
return err
@@ -61,6 +70,12 @@ the prompt (required in agent / CI / piped contexts).`,
}
func runDelete(ctx context.Context, opts *DeleteOptions, svc DeleteService, p prompt.Prompter, id string) error {
if opts.DryRun {
return cmdutil.EmitDryRun(opts.JSONOut,
deleteResult{ID: id, Deleted: false}, nil,
&format.Risk{Level: format.RiskHighRiskWrite, Action: fmt.Sprintf("delete document %s", id)})
}
if err := cmdutil.ConfirmDestructive(p, opts.Yes, opts.JSONOut, "document", id); err != nil {
return err
}
@@ -70,7 +85,8 @@ func runDelete(ctx context.Context, opts *DeleteOptions, svc DeleteService, p pr
}
if opts.JSONOut {
return format.WriteEnvelope(iostreams.IO.Out, format.Success(deleteResult{ID: id, Deleted: true}, nil))
risk := &format.Risk{Level: format.RiskHighRiskWrite, Action: fmt.Sprintf("deleted document %s", id)}
return format.WriteEnvelope(iostreams.IO.Out, format.SuccessWithRisk(deleteResult{ID: id, Deleted: true}, nil, risk))
}
fmt.Fprintf(iostreams.IO.Out, "✓ Deleted document %s\n", id)
return nil
+11 -8
View File
@@ -128,15 +128,18 @@ func TestDelete_AgentPrompterErrors(t *testing.T) {
assert.Equal(t, cmdutil.CodeInputMissingFlag, typed.Code)
}
// TestDelete_NoForce_NonTTY_Proceeds: when stdout isn't a TTY (typical agent
// pipe / CI), the confirm guard is skipped. This documents the existing
// contract — destructive ops in a pipe rely on the caller having chosen to
// pipe (intent expressed by the redirection) and on agents passing --force
// explicitly. Mirrors `weknora kb delete`.
func TestDelete_NoForce_NonTTY_Proceeds(t *testing.T) {
// TestDelete_NoYes_NonTTY_RequiresConfirmation: when stdout isn't a TTY
// (typical agent pipe / CI), the lark-cli skill protocol requires explicit
// -y/--yes. The CLI exits 10 with input.confirmation_required, never
// silently proceeds. See cli/AGENTS.md "Exit codes".
func TestDelete_NoYes_NonTTY_RequiresConfirmation(t *testing.T) {
_, _ = iostreams.SetForTest(t)
svc := &fakeDeleteSvc{}
err := runDelete(context.Background(), &DeleteOptions{Yes: false}, svc, errPrompter{}, "doc_abc")
require.NoError(t, err, "non-TTY non-json invocation should proceed without prompting")
assert.Equal(t, 1, svc.calls)
require.Error(t, err)
var typed *cmdutil.Error
require.ErrorAs(t, err, &typed)
assert.Equal(t, cmdutil.CodeInputConfirmationRequired, typed.Code)
assert.Equal(t, 0, svc.calls, "non-TTY without -y must not call DeleteKnowledge")
assert.Equal(t, 10, cmdutil.ExitCode(err))
}
+14 -1
View File
@@ -23,6 +23,7 @@ const uploadChannel = "api"
type UploadOptions struct {
Name string
JSONOut bool
DryRun bool
}
// UploadService is the narrow SDK surface this command depends on.
@@ -62,10 +63,14 @@ planned for v0.3.`,
if err := validateUploadPath(path); err != nil {
return err
}
opts.DryRun = cmdutil.IsDryRun(c)
kbID, err := f.ResolveKB(c)
if err != nil {
return err
}
if opts.DryRun {
return runUpload(c.Context(), opts, nil, kbID, path)
}
cli, err := f.Client()
if err != nil {
return err
@@ -104,13 +109,21 @@ func validateUploadPath(path string) error {
}
func runUpload(ctx context.Context, opts *UploadOptions, svc UploadService, kbID, path string) error {
if opts.DryRun {
return cmdutil.EmitDryRun(opts.JSONOut,
map[string]string{"file": path, "kb_id": kbID, "name": opts.Name},
&format.Meta{KBID: kbID},
&format.Risk{Level: format.RiskWrite, Action: fmt.Sprintf("upload %s to kb %s", path, kbID)})
}
k, err := svc.CreateKnowledgeFromFile(ctx, kbID, path, nil /*metadata*/, nil /*enableMultimodel*/, opts.Name, uploadChannel)
if err != nil {
return cmdutil.Wrapf(cmdutil.ClassifyHTTPError(err), err, "upload %s", path)
}
if opts.JSONOut {
return format.WriteEnvelope(iostreams.IO.Out, format.Success(k, &format.Meta{KBID: kbID}))
risk := &format.Risk{Level: format.RiskWrite, Action: fmt.Sprintf("uploaded %s", path)}
return format.WriteEnvelope(iostreams.IO.Out, format.SuccessWithRisk(k, &format.Meta{KBID: kbID}, risk))
}
displayed := opts.Name
if displayed == "" {