Skip to content

Improve OKR shortcuts#1487

Merged
syh-cpdsss merged 7 commits into
mainfrom
feat/okr-shortcuts
Jun 18, 2026
Merged

Improve OKR shortcuts#1487
syh-cpdsss merged 7 commits into
mainfrom
feat/okr-shortcuts

Conversation

@syh-cpdsss

@syh-cpdsss syh-cpdsss commented Jun 16, 2026

Copy link
Copy Markdown
Collaborator

Summary

This PR adds four new OKR shortcuts to streamline common OKR management operations: +batch-create, +reorder, +weight, and +indicator-update, improving success rates and reduce token usage for end-to-end OKR workflows.

Changes

  • +batch-create shortcut (shortcuts/okr/okr_batch_create.go): Atomic batch creation of Objectives and Key Results with automatic rollback on failure. Supports @mention in content, file/stdin input via @path/@-, and --dry-run for preview.
  • +reorder shortcut (shortcuts/okr/okr_reorder.go): Position-based reordering for both Objectives (cycle-level) and Key Results (objective-level). Accepts partial position changes and automatically constructs the full ordered ID list required by the native objectives_position/key_results_position APIs.
  • +weight shortcut (shortcuts/okr/okr_weight.go): Smart weight allocation for Objectives and KRs. Supports partial weight specification with automatic normalization of unspecified items based on original weight proportions, ensuring the total always equals 1.0.
  • +indicator-update shortcut (shortcuts/okr/okr_indicator_update.go): Simplified indicator current value update. Automatically looks up the indicator ID for a given Objective/KR ID and updates the current_value field, eliminating the need for a separate indicator list API call.
  • Skill documentation (skills/lark-okr/SKILL.md): Added all four shortcuts to the Shortcuts table with links to detailed reference docs.
  • Reference documentation: Added comprehensive usage docs for each shortcut (lark-okr-batch-create.md, lark-okr-reorder.md, lark-okr-weight.md, lark-okr-indicator-update.md) including command examples, parameter tables, input/output formats, and workflow guidance.
  • Unit tests: Added comprehensive test coverage for all four shortcuts (4594 lines across implementation and test files), covering success paths, edge cases, validation errors, and rollback scenarios.
  • E2E tests: Added tests/cli_e2e/okr/okr_shortcuts_test.go with dry-run and live E2E tests validating the complete shortcut request/response flow.
  • Shortcut registration: Registered all four new shortcuts in shortcuts/okr/shortcuts.go.

Test Plan

  • Unit tests pass
  • Manual Test & evaluation pass

Related Issues

  • None

Summary by CodeRabbit

Release Notes

  • New Features
    • Added okr +batch-create to batch-create OKR objectives and key results from JSON, with validation, optional mentions, dry-run planning, and rollback on failures.
    • Added okr +indicator-update to update an indicator’s current_value at objective or key-result level, including dry-run support.
    • Added okr +reorder to reorder objectives or key results via --ops, with dry-run previews.
    • Added okr +weight to set objective/key-result weights with validation and normalization to a total of 1.0, plus dry-run.
  • Documentation
    • Added reference docs and updated the shortcuts table for the new commands.
  • Tests
    • Added unit and CLI end-to-end coverage for validation, dry-run output, and live behavior (including rollback/error paths).

Add three new OKR shortcuts for managing objectives and key results:

- +batch-create: Bulk create objectives with key results, with automatic
  rollback on failure
- +reorder: Adjust position of objectives or key results within a cycle/objective
- +weight: Adjust weights of objectives or key results with automatic
  normalization using fixed-point arithmetic to avoid float precision issues

Key implementation details:
- API paths use underscore separators (/objectives_position, /objectives_weight)
- Weight normalization uses json.Number for precise JSON serialization
- Items are sorted by position before API calls to match backend requirements
- Full unit test coverage and dry-run/live E2E tests
- Skill documentation with usage examples and parameter descriptions

Change-Id: I92b658e0cc42ffa8cbdaec2ec628a079bcfc38f5
Change-Id: I862190b066fb98276ef28d5d6d47063a9a3ef3ae
@coderabbitai

coderabbitai Bot commented Jun 16, 2026

Copy link
Copy Markdown

Review Change Stack

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

Adds four new OKR CLI shortcut commands (+batch-create, +reorder, +weight, +indicator-update) to the shortcuts/okr package, each with validation, dry-run, and execute behaviors. All four are registered in Shortcuts(), covered by unit and integration tests, documented in reference Markdown files, and tested via E2E and dry-run assertions.

Changes

OKR Shortcut Commands

Layer / File(s) Summary
Shortcut registration and skill index
shortcuts/okr/shortcuts.go, skills/lark-okr/SKILL.md
Shortcuts() returns OKRBatchCreate, OKRReorder, OKRWeight, OKRIndicatorUpdate; SKILL.md shortcut table expanded to include all four new entries.
+batch-create: implementation
shortcuts/okr/okr_batch_create.go
Defines batch-create input structs, parseBatchCreateInput, buildContentBlock, createObjective/createKR API helpers, deleteObjective/rollback with rate limiting, buildRollbackError, and OKRBatchCreate with Validate/DryRun/Execute.
+batch-create: tests and reference docs
shortcuts/okr/okr_batch_create_test.go, skills/lark-okr/references/lark-okr-batch-create.md
Full test suite covering validation, dry-run, execute success envelope, API error and rollback trigger cases, rollback-failure residual-ID reporting, and unit tests for parseBatchCreateInput and buildContentBlock. Reference documentation with command examples, parameters, workflow, and output structure.
+reorder: implementation
shortcuts/okr/okr_reorder.go
Defines reorderItem interface, parseReorderOps, fetchObjectives/fetchKeyResults (paginated + position-sorted), buildReorderedIDs with clamping, GetID() on Objective/KeyResult, and OKRReorder with Validate/DryRun/Execute.
+reorder: tests and reference docs
shortcuts/okr/okr_reorder_test.go, skills/lark-okr/references/lark-okr-reorder.md
Validation tests (level, ops JSON/semantic), dry-run endpoint assertions for objective and key-result levels, execute success/clamping/not-found scenarios, and unit tests for parseReorderOps and buildReorderedIDs. Reference documentation with command examples, constraints, parameters, and workflow.
+weight: implementation
shortcuts/okr/okr_weight.go
Defines parseWeightOps with decimal/sum constraints, formatWeight (3-decimal precision), normalizeWeights (×1000 fixed-point with proportional distribution), GetWeight() on Objective/KeyResult, and OKRWeight with Validate/DryRun/Execute.
+weight: tests and reference docs
shortcuts/okr/okr_weight_test.go, skills/lark-okr/references/lark-okr-weight.md
Validation, dry-run endpoint/body assertions, execute weight-sum verification and not-found error, and unit tests for parseWeightOps and normalizeWeights. Reference documentation with prerequisites, examples, weight rules, normalization behavior, and workflow.
+indicator-update: implementation
shortcuts/okr/okr_indicator_update.go
Defines parseIndicatorValue, fetchIndicatorID (GET indicators endpoint), and OKRIndicatorUpdate with Validate/DryRun/Execute (two-step GET-then-PATCH).
+indicator-update: tests and reference docs
shortcuts/okr/okr_indicator_update_test.go, skills/lark-okr/references/lark-okr-indicator-update.md
Validation, execute success for objective and key-result levels with GET+PATCH stubs, API error handling, and parseIndicatorValue unit tests. Reference documentation with command examples, parameters, workflow, output structure, and constraints.
E2E tests: dry-run and live integration
tests/cli_e2e/okr/okr_shortcuts_test.go
Dry-run tests asserting stdout endpoint path fragments for all three non-indicator shortcuts; live tests gated by OKR_TEST_CYCLE_ID with createTestObjectives, cleanupLiveTest helpers, and end-to-end assertions for batch-create, reorder, and weight with correctness verification and weight-sum tolerance checks.

Sequence Diagram(s)

sequenceDiagram
  participant User as CLI User
  participant BatchCreate as +batch-create Execute
  participant API as Lark OKR v2 API
  participant Rollback as rollback()

  User->>BatchCreate: --cycle-id --input JSON
  loop for each objective
    BatchCreate->>API: POST /okr/v2/objectives
    API-->>BatchCreate: objective_id
    loop for each key result
      BatchCreate->>API: POST /okr/v2/objectives/{id}/key_results
      alt KR creation fails
        API-->>BatchCreate: error
        BatchCreate->>Rollback: delete created objectives (reverse)
        Rollback->>API: DELETE /okr/v2/objectives/{id}
        Rollback-->>BatchCreate: deletion results
        BatchCreate-->>User: rollback error + residual IDs
      else success
        API-->>BatchCreate: key_result_id
      end
    end
  end
  BatchCreate-->>User: ok=true, data.created[{objective_id, krs}]
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Possibly related PRs

  • larksuite/cli#522: Extends the OKR shortcut registry to include +batch-create, +reorder, +weight, and +indicator-update commands, building on the OKR domain and cycle-list/detail shortcuts.

Suggested labels

feature

Suggested reviewers

  • zhangzq0

Poem

🐇 Four new commands hopped into place,
+batch-create, +reorder, +weight with grace,
+indicator-update joined the crew,
Rollback, normalization, dry-run too!
The OKR warren grows wide and bright,
Every objective ordered just right. ✨

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (1 warning, 1 inconclusive)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 40.91% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
Title check ❓ Inconclusive The title 'Improve OKR shortcuts' is vague and overly generic, using a non-descriptive term that does not convey meaningful information about the specific changes. Replace with a more specific title that clearly identifies the main change, such as 'Add four new OKR shortcuts: batch-create, reorder, weight, and indicator-update' or similar.
✅ Passed checks (3 passed)
Check name Status Explanation
Description check ✅ Passed The PR description is comprehensive and well-structured, covering all required sections: Summary (motivation/scope), detailed Changes list with specific features, Test Plan with checkboxes, and Related Issues. It exceeds template minimums with thorough explanations of each new shortcut's functionality.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feat/okr-shortcuts

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

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@github-actions github-actions Bot added the size/XL Architecture-level or global-impact change label Jun 16, 2026
Change-Id: I3f27a01cdae2122f26e48ee2acb7f334f2bab7d2
@syh-cpdsss syh-cpdsss force-pushed the feat/okr-shortcuts branch from 0af7c85 to 6e2b7fc Compare June 16, 2026 11:37
@github-actions

github-actions Bot commented Jun 16, 2026

Copy link
Copy Markdown

🚀 PR Preview Install Guide

🧰 CLI update

npm i -g https://pkg.pr.new/larksuite/cli/@larksuite/cli@b896fd8b82445f89571f896d3225f382680fc9a5

🧩 Skill update

npx skills add larksuite/cli#feat/okr-shortcuts -y -g

@codecov

codecov Bot commented Jun 16, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 79.39394% with 170 lines in your changes missing coverage. Please review.
✅ Project coverage is 73.78%. Comparing base (1f2164c) to head (b896fd8).

Files with missing lines Patch % Lines
shortcuts/okr/okr_weight.go 80.21% 33 Missing and 22 partials ⚠️
shortcuts/okr/okr_reorder.go 79.76% 31 Missing and 20 partials ⚠️
shortcuts/okr/okr_indicator_update.go 59.78% 32 Missing and 5 partials ⚠️
shortcuts/okr/okr_batch_create.go 86.43% 21 Missing and 6 partials ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main    #1487      +/-   ##
==========================================
+ Coverage   73.72%   73.78%   +0.06%     
==========================================
  Files         781      785       +4     
  Lines       74217    75042     +825     
==========================================
+ Hits        54717    55372     +655     
- Misses      15437    15554     +117     
- Partials     4063     4116      +53     

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

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 17

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
shortcuts/okr/okr_indicator_update_test.go (1)

43-363: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Dry-run behavior is missing dedicated test coverage.

+indicator-update has a two-step dry-run plan (GET indicators + PATCH template), but this file has no --dry-run assertion for endpoint/body rendering. Add one to cover request structure/output for this behavior path.

As per coding guidelines, every behavior change needs a test alongside the change.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@shortcuts/okr/okr_indicator_update_test.go` around lines 43 - 363, Add test
coverage for the dry-run behavior of the indicator-update shortcut. Create test
functions that verify the --dry-run flag behavior by testing both the GET
indicators request and the PATCH template rendering without actually executing
the API calls. These tests should assert that the endpoint calls are prepared
correctly and that the output shows the request structure (URL, method, body)
that would be executed, similar to the existing validation and execution tests
(TestIndicatorUpdateValidate_Valid,
TestIndicatorUpdateExecute_Objectives_Success, etc.). Include separate test
cases for both objective and key-result levels to ensure the dry-run behavior
works correctly for different endpoint paths.

Source: Coding guidelines

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@shortcuts/okr/okr_batch_create_test.go`:
- Around line 457-460: The rollback error-path assertion currently only checks
error message substrings for "rolling back" or "rollback". Strengthen this test
by also asserting the error's typed metadata using errs.ProblemOf(err) to verify
the category and subtype fields match expected values, and assert cause
preservation using errors.Unwrap() or errors.Is() to ensure the underlying error
is properly wrapped and propagated. Apply this same pattern of typed assertions
plus cause checks instead of message substrings at all affected error validation
locations.

In `@shortcuts/okr/okr_batch_create.go`:
- Around line 348-364: The loop that populates residualIDs (lines 348-352)
unconditionally appends all created objectives regardless of whether rollback
succeeded or failed. Modify this loop to only collect objective IDs into
residualIDs when rollback actually failed or was not attempted. This typically
means adding a conditional check before the loop to only execute it when
len(rollbackErrs) > 0 (indicating rollback had failures), so users are not
instructed to manually clean up objectives that were already successfully
deleted during a completed rollback.
- Around line 345-367: The buildRollbackError function currently downgrades
typed errors by always returning errs.NewInternalError with SubtypeUnknown,
regardless of the actual error type from originalErr. Instead of creating a new
InternalError, extract the error type and subtype from originalErr and preserve
it when constructing the return error. If originalErr is already a properly
typed error, use its type information in the error creation rather than
overriding it with SubtypeUnknown. This ensures that API/network failures
maintain their original classification rather than being reclassified as generic
internal errors.

In `@shortcuts/okr/okr_indicator_update_test.go`:
- Around line 279-300: The test functions
TestIndicatorUpdateExecute_FetchAPIError (at lines 279-300) and the patch
failure test (at lines 302-337) currently only check for non-nil errors without
asserting typed problem metadata. Replace the weak `if err == nil` checks with
typed assertions using errs.ProblemOf(err) to verify the error category and
subtype, and additionally assert the presence of unwrap or cause information to
properly lock in the error contract behavior as required by the coding
guidelines.

In `@shortcuts/okr/okr_indicator_update.go`:
- Around line 71-73: The flags "level", "id", and "value" are using Required:
true which causes missing-flag failures to be handled as plain errors by Cobra
instead of following the typed error contract. Remove the Required: true
attribute from all three flag definitions in the diff section, then add
corresponding validation logic in the Validate method that checks if these flags
are provided and returns typed errs.NewValidationError with WithParam metadata
for each missing required flag instead of relying on Cobra's error handling.
- Around line 19-22: The validation error returned when strconv.ParseFloat fails
does not preserve the underlying parse error, which breaks error cause chain
diagnostics. Split the condition checking so that parse errors (when err != nil
from ParseFloat) are handled separately from range/NaN/Inf validation checks.
For the parse error case, attach the actual error using .WithCause(err) to
preserve the error chain. The range/NaN/Inf checks can remain combined or
separate as appropriate, but only the parse failure path needs the cause
attachment.

In `@shortcuts/okr/okr_reorder_test.go`:
- Around line 142-165: The test TestReorderValidate_InvalidOpsJSON currently
verifies the error type and param but does not assert the category and subtype
metadata via errs.ProblemOf, and does not verify that the invalid-JSON cause is
preserved in the error chain. Strengthen the assertion by capturing the problem
returned from errs.ProblemOf(err) and assert its category and subtype fields
match expected values. Additionally, assert that the error wraps the underlying
JSON parsing error by checking the error's Unwrap() method or cause chain. Apply
the same strengthened assertions to the similar tests at lines 192-246 and
504-546, ensuring all error-path tests verify typed metadata and cause
preservation rather than relying solely on message substrings.

In `@shortcuts/okr/okr_reorder.go`:
- Around line 68-73: The pagination loop uses a fixed time.Sleep() call that
ignores context cancellation, preventing users from cleanly canceling long
pagination operations. Replace the time.Sleep() with a context-aware sleep
mechanism using a select statement that checks both ctx.Done() and a timer
channel. This allows the sleep to be interrupted immediately when the context is
canceled, enabling graceful cancellation of the pagination flow. Apply this fix
to all occurrences of the fixed sleep pattern in the pagination loops.
- Around line 245-249: Remove the Required: true constraint from the level,
cycle-id, and ops flags in the reorder command configuration, as this causes
Cobra to fail with non-typed errors before the Validate function executes.
Instead, move the validation logic into the Validate function for the reorder
command to check that these three flags are present and return properly typed
errs.* errors when they are missing, ensuring command-facing failures use typed
validation errors as per coding guidelines.

In `@shortcuts/okr/okr_weight_test.go`:
- Around line 83-93: The error-path tests are not asserting the full typed error
contract as required by coding guidelines. While the tests check that
errs.ProblemOf returns successfully and verify the Param field, they do not
assert the actual category and subtype values returned by errs.ProblemOf, and
wrapped error paths do not verify cause preservation. For all affected locations
(in the ranges 83-93, 122-132, 161-171, 186-196, 211-221, 239-249, 264-274,
292-302, 320-330, and 556-566 in okr_weight_test.go), enhance the error
assertions to capture and validate the Problem object returned by
errs.ProblemOf, then assert both the category and subtype fields match the
expected values. For any tests that involve error wrapping, add additional
assertions to verify that the cause error is correctly preserved in the error
chain. This ensures all error-path tests comprehensively validate the full typed
error contract rather than only checking Param.
- Around line 33-40: The weightTestConfig helper function is missing environment
isolation for test configuration state. Add a call to
t.Setenv("LARKSUITE_CLI_CONFIG_DIR", t.TempDir()) at the beginning of the
weightTestConfig function to ensure each test gets an isolated temporary
configuration directory, following the coding guidelines for test config
isolation.

In `@shortcuts/okr/okr_weight.go`:
- Around line 483-487: The weightEntry["weight"] value is a json.Number type,
but the format string %.3f in the fprintf call expects a float64. Convert the
json.Number to float64 before formatting it in the fprintf statement at line
486. Use the appropriate method to parse the json.Number value to a float64 and
handle any conversion errors that may occur.

In `@skills/lark-okr/references/lark-okr-indicator-update.md`:
- Line 42: The CLI command notation on this line is inconsistent with earlier
examples in the document. Line 42 uses dot notation (objective.indicators.list
and key_result.indicators.list) while earlier examples use space-separated
notation (objective.indicators list and key_result.indicators list). Update line
42 to use the space-separated format consistently with the earlier examples to
prevent confusion and copy/paste errors for users.

In `@skills/lark-okr/references/lark-okr-reorder.md`:
- Around line 46-47: The documentation for the lark-okr-reorder command contains
inaccuracies. Review the actual implementation to clarify the requirements for
the --cycle-id parameter and its conditional necessity. Update the parameter
description for --cycle-id at lines 46-47 to accurately reflect when it is
required versus optional. Additionally, update the sample response section to
match the actual implementation output fields, replacing the incorrect fields
(cycle_id, new_order) with the actual output fields (level, total, ordered).
Apply these same corrections to all affected locations including the areas
around lines 61-75 to ensure the documentation is consistent throughout.

In `@skills/lark-okr/references/lark-okr-weight.md`:
- Around line 71-83: The JSON response example in the lark-okr-weight.md
documentation includes a `cycle_id` field within the `data` object, but the
actual Execute implementation does not return this field. Remove the `cycle_id`
field from the example response block (which currently shows `"cycle_id":
"7000000000000000001"`) so that the documented output schema matches the actual
CLI implementation that only returns `level`, `total`, and `weights` fields.
- Around line 20-29: The section header "调整 KR 权重(全部指定,和为 1)" indicates weights
should sum to 1.0, but the example shows weights of 0.5 and 0.3 which sum to
only 0.8. Fix this inconsistency by either adjusting the weight values in the
example to sum to exactly 1.0 (for instance, change the second weight from 0.3
to 0.5 to make the total 1.0), or change the section header from "全部指定,和为 1" to
"部分指定" to accurately reflect that the example is showing partial weight
specification. Choose the option that matches the intent of the documentation.

In `@tests/cli_e2e/okr/okr_shortcuts_test.go`:
- Around line 289-294: The cleanup registration for the `cleanupLiveTest()`
function must be moved to execute immediately after resource creation by
`createTestObjectives()`, before any assertions that could fail. Currently, if
`createTestObjectives()` internally fails on a `require.*` check after creating
resources (as noted in Lines 225-229), the test terminates before cleanup is
ever registered. To fix this across all affected sites (lines 289-294, 338-345,
and 399-406), either move all assertions out of `createTestObjectives()` to
happen after cleanup registration, or refactor `createTestObjectives()` to
return an error value and always call `t.Cleanup()` immediately after the
function returns, before performing any assertions on the created objects.

---

Outside diff comments:
In `@shortcuts/okr/okr_indicator_update_test.go`:
- Around line 43-363: Add test coverage for the dry-run behavior of the
indicator-update shortcut. Create test functions that verify the --dry-run flag
behavior by testing both the GET indicators request and the PATCH template
rendering without actually executing the API calls. These tests should assert
that the endpoint calls are prepared correctly and that the output shows the
request structure (URL, method, body) that would be executed, similar to the
existing validation and execution tests (TestIndicatorUpdateValidate_Valid,
TestIndicatorUpdateExecute_Objectives_Success, etc.). Include separate test
cases for both objective and key-result levels to ensure the dry-run behavior
works correctly for different endpoint paths.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: a6b2c597-ef81-41c1-b4f7-5f0a0db27112

📥 Commits

Reviewing files that changed from the base of the PR and between 4464ba7 and 6e2b7fc.

📒 Files selected for processing (15)
  • shortcuts/okr/okr_batch_create.go
  • shortcuts/okr/okr_batch_create_test.go
  • shortcuts/okr/okr_indicator_update.go
  • shortcuts/okr/okr_indicator_update_test.go
  • shortcuts/okr/okr_reorder.go
  • shortcuts/okr/okr_reorder_test.go
  • shortcuts/okr/okr_weight.go
  • shortcuts/okr/okr_weight_test.go
  • shortcuts/okr/shortcuts.go
  • skills/lark-okr/SKILL.md
  • skills/lark-okr/references/lark-okr-batch-create.md
  • skills/lark-okr/references/lark-okr-indicator-update.md
  • skills/lark-okr/references/lark-okr-reorder.md
  • skills/lark-okr/references/lark-okr-weight.md
  • tests/cli_e2e/okr/okr_shortcuts_test.go

Comment thread shortcuts/okr/okr_batch_create_test.go
Comment thread shortcuts/okr/okr_batch_create.go
Comment thread shortcuts/okr/okr_batch_create.go Outdated
Comment thread shortcuts/okr/okr_indicator_update_test.go
Comment thread shortcuts/okr/okr_indicator_update.go
Comment thread skills/lark-okr/references/lark-okr-indicator-update.md Outdated
Comment thread skills/lark-okr/references/lark-okr-reorder.md Outdated
Comment thread skills/lark-okr/references/lark-okr-weight.md
Comment thread skills/lark-okr/references/lark-okr-weight.md
Comment thread tests/cli_e2e/okr/okr_shortcuts_test.go
Change-Id: Id9fab84e06f0d67e9f79c1fb9946b6b633200592

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
shortcuts/okr/okr_weight_test.go (1)

507-520: ⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Strengthen execute success checks with per-ID weight assertions.

Current assertions can pass even if allocation is wrong but still sums to 1.0. Add assertions for expected IDs and at least the explicitly specified weight values (e.g., objective id=1 should remain 0.7, key-result id=kr1 should remain 0.5), plus expected list length.

💡 Minimal assertion hardening
@@
-	weights, _ := data["weights"].([]interface{})
+	weights, _ := data["weights"].([]interface{})
 	if len(weights) != 2 {
 		t.Fatalf("expected 2 items in weights list, got %d", len(weights))
 	}
+	byID := map[string]float64{}
+	for _, w := range weights {
+		wm, _ := w.(map[string]interface{})
+		id, _ := wm["id"].(string)
+		byID[id] = getWeightFloat(wm["weight"])
+	}
+	if math.Abs(byID["1"]-0.7) > 1e-9 {
+		t.Fatalf("expected id=1 weight=0.7, got %.10f", byID["1"])
+	}
@@
-	weights, _ := data["weights"].([]interface{})
+	weights, _ := data["weights"].([]interface{})
+	if len(weights) != 3 {
+		t.Fatalf("expected 3 items in weights list, got %d", len(weights))
+	}
+	byID := map[string]float64{}
+	for _, w := range weights {
+		wm, _ := w.(map[string]interface{})
+		id, _ := wm["id"].(string)
+		byID[id] = getWeightFloat(wm["weight"])
+	}
+	if math.Abs(byID["kr1"]-0.5) > 1e-9 {
+		t.Fatalf("expected kr1 weight=0.5, got %.10f", byID["kr1"])
+	}

Also applies to: 577-588

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@shortcuts/okr/okr_weight_test.go` around lines 507 - 520, The current test
assertions in the weight verification blocks are insufficient as they only
validate that two items exist and sum to 1.0, but do not verify that each
specific item has the correct weight assigned to it. Add assertions after the
length check to verify the expected IDs and their corresponding weight values
are present in the weights list. For each weight element retrieved from the
weights list, extract both the ID (using a key like "id") and the weight value
(already being extracted via getWeightFloat), then assert that objective id=1
has weight 0.7 and key-result id=kr1 has weight 0.5. Apply this hardening to
both affected test sections (around lines 507-520 and 577-588) to ensure
allocation correctness beyond just sum validation.
🧹 Nitpick comments (2)
shortcuts/okr/okr_reorder_test.go (2)

166-168: 💤 Low value

Tautological errors.Is checks after errors.As succeeds.

After errors.As(err, &validationErr) succeeds and assigns validationErr, the subsequent errors.Is(err, validationErr) is always true by definition—if err contains validationErr (found by As), then Is will find it too. These checks don't add value and can be removed.

Also applies to: 222-224, 256-258, 568-570

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@shortcuts/okr/okr_reorder_test.go` around lines 166 - 168, Remove the
redundant errors.Is checks that appear after successful errors.As calls in the
test file, as they are tautological—once errors.As succeeds in finding and
assigning validationErr, errors.Is will always return true by definition. Delete
the if statements checking errors.Is at lines 166-168, 222-224, 256-258, and
568-570 since they do not add value to the test assertions.

51-63: 💤 Low value

Missing-flag tests rely on string matching instead of typed errors.

These tests check for flag names in error messages via strings.Contains, which works but doesn't verify the error is typed. Since the implementation now uses typed errs.NewValidationError for these cases (per the flag validation changes), consider updating these tests to assert typed metadata.

However, if these tests are intentionally covering the case where Cobra's enum validation fails before Validate runs (for --level), the current approach is acceptable since Cobra errors aren't typed.

Also applies to: 90-102, 129-141

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@shortcuts/okr/okr_reorder_test.go` around lines 51 - 63, The test
`TestReorderValidate_MissingLevel` (and similar tests referenced at lines 90-102
and 129-141) currently rely on `strings.Contains` to verify error messages,
which doesn't validate the error type. Since the implementation now uses typed
`errs.NewValidationError` for validation cases, determine whether this specific
test is verifying Cobra's built-in enum validation (which occurs before the
custom Validate method and is not typed) or custom validation (which should use
the typed error). If the test is checking custom validation errors created with
`errs.NewValidationError`, update the assertion to verify the typed error
metadata instead of string matching the error message. If this test is
intentionally covering Cobra's pre-validation behavior, the current string
matching approach can remain acceptable and this can be documented.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Outside diff comments:
In `@shortcuts/okr/okr_weight_test.go`:
- Around line 507-520: The current test assertions in the weight verification
blocks are insufficient as they only validate that two items exist and sum to
1.0, but do not verify that each specific item has the correct weight assigned
to it. Add assertions after the length check to verify the expected IDs and
their corresponding weight values are present in the weights list. For each
weight element retrieved from the weights list, extract both the ID (using a key
like "id") and the weight value (already being extracted via getWeightFloat),
then assert that objective id=1 has weight 0.7 and key-result id=kr1 has weight
0.5. Apply this hardening to both affected test sections (around lines 507-520
and 577-588) to ensure allocation correctness beyond just sum validation.

---

Nitpick comments:
In `@shortcuts/okr/okr_reorder_test.go`:
- Around line 166-168: Remove the redundant errors.Is checks that appear after
successful errors.As calls in the test file, as they are tautological—once
errors.As succeeds in finding and assigning validationErr, errors.Is will always
return true by definition. Delete the if statements checking errors.Is at lines
166-168, 222-224, 256-258, and 568-570 since they do not add value to the test
assertions.
- Around line 51-63: The test `TestReorderValidate_MissingLevel` (and similar
tests referenced at lines 90-102 and 129-141) currently rely on
`strings.Contains` to verify error messages, which doesn't validate the error
type. Since the implementation now uses typed `errs.NewValidationError` for
validation cases, determine whether this specific test is verifying Cobra's
built-in enum validation (which occurs before the custom Validate method and is
not typed) or custom validation (which should use the typed error). If the test
is checking custom validation errors created with `errs.NewValidationError`,
update the assertion to verify the typed error metadata instead of string
matching the error message. If this test is intentionally covering Cobra's
pre-validation behavior, the current string matching approach can remain
acceptable and this can be documented.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 0e6aa937-a2d0-4b48-97d3-7a1950348eef

📥 Commits

Reviewing files that changed from the base of the PR and between 6e2b7fc and b96cc8d.

📒 Files selected for processing (12)
  • shortcuts/okr/okr_batch_create.go
  • shortcuts/okr/okr_batch_create_test.go
  • shortcuts/okr/okr_indicator_update.go
  • shortcuts/okr/okr_indicator_update_test.go
  • shortcuts/okr/okr_reorder.go
  • shortcuts/okr/okr_reorder_test.go
  • shortcuts/okr/okr_weight.go
  • shortcuts/okr/okr_weight_test.go
  • skills/lark-okr/references/lark-okr-indicator-update.md
  • skills/lark-okr/references/lark-okr-reorder.md
  • skills/lark-okr/references/lark-okr-weight.md
  • tests/cli_e2e/okr/okr_shortcuts_test.go
✅ Files skipped from review due to trivial changes (1)
  • skills/lark-okr/references/lark-okr-reorder.md
🚧 Files skipped from review as they are similar to previous changes (7)
  • skills/lark-okr/references/lark-okr-weight.md
  • shortcuts/okr/okr_batch_create.go
  • shortcuts/okr/okr_weight.go
  • shortcuts/okr/okr_batch_create_test.go
  • shortcuts/okr/okr_indicator_update.go
  • tests/cli_e2e/okr/okr_shortcuts_test.go
  • shortcuts/okr/okr_indicator_update_test.go

Change-Id: I6a5e57dd4b10dc79f8681ec614354fbba82abc04
@syh-cpdsss syh-cpdsss force-pushed the feat/okr-shortcuts branch from 9c04e34 to 09a97d8 Compare June 17, 2026 06:02
Change-Id: I6e2a39269e62e3b504e681110843b2ccc315a527
Change-Id: I81dcdf5f89edd5b5c2277b8391b59dd79cc581aa
@syh-cpdsss syh-cpdsss merged commit 83db159 into main Jun 18, 2026
23 checks passed
@syh-cpdsss syh-cpdsss deleted the feat/okr-shortcuts branch June 18, 2026 08:25
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

size/XL Architecture-level or global-impact change

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants