diff --git a/.agents/skills/issue-spec-feedback/SKILL.md b/.agents/skills/issue-spec-feedback/SKILL.md new file mode 100644 index 00000000..add320e2 --- /dev/null +++ b/.agents/skills/issue-spec-feedback/SKILL.md @@ -0,0 +1,16 @@ +--- +name: issue-spec-feedback +description: Capture reproducible friction from any project skill, CLI command, or workflow. Use when instructions, references, or scripts cause a concrete problem during work. +license: MIT +metadata: + requires: "Requires issue-spec CLI." + author: issue-spec + version: "1.0" + generatedBy: "issue-spec" +--- + +# Issue Spec Feedback + +When a skill's instructions, references, or scripts cause a reproducible problem, record the skill name, repository-relative path, applicable revision, observed behavior, and impact on the task. Direct the report to the repository that owns the cause. + +Follow the [feedback guide](../issue-spec-workflow/references/workflow-feedback.md) to load project guidance, verify the Issue destination, and record evidence. Issue writes use the task's authorization and the target backend's permissions. diff --git a/.agents/skills/issue-spec-workflow/SKILL.md b/.agents/skills/issue-spec-workflow/SKILL.md index 0c9e45a2..fd3f51a4 100644 --- a/.agents/skills/issue-spec-workflow/SKILL.md +++ b/.agents/skills/issue-spec-workflow/SKILL.md @@ -22,6 +22,8 @@ For selected issue-spec steps, the built-in phase sequence and canonical artifac 3. Default to `--issue` for a bounded change with one code writer. A single child or subagent is an execution choice, not a reason to create TASK or PROCESS. Use `--proposal` with optional `--design` and `--implement` only when product, design, or concrete coordination risk requires them. File count does not select the path. 4. Read only selected issue bodies and typed planning artifacts. Historical REVIEW, VERIFY, evidence, receipt, finalization, Archive, and merge-authority data are explicit read-only audit history. +When authorized work exposes evidence-backed CLI, workflow, or project skill friction, use [Workflow feedback](references/workflow-feedback.md). Project guidance may refine routing and write authorization. + ## Optional Planning and Implementation - Create Proposal, Design, Implement, and TASK only when product, design, or coordination risk makes that planning useful. Create PROCESS only when a concrete execution need requires managed coordination: concurrent code writers, protection of pre-existing work through isolation, enforced path ownership, restartable cross-session handoff, or dependency-ordered integration. Generate selected canonical SPEC, QUESTION, TASK, and PROCESS planning artifacts; transition existing artifacts instead of regenerating them. diff --git a/.agents/skills/issue-spec-workflow/references/workflow-feedback.md b/.agents/skills/issue-spec-workflow/references/workflow-feedback.md new file mode 100644 index 00000000..5c4008bc --- /dev/null +++ b/.agents/skills/issue-spec-workflow/references/workflow-feedback.md @@ -0,0 +1,72 @@ +# Workflow feedback + +Use this reference when authorized work exposes a reproducible problem with a project skill, CLI command, or workflow. The standalone `issue-spec-feedback` skill also links to this reference during ordinary project tasks. Continue the original task and use an ordinary Issue and comments. Apply the current task's publication authorization and any standing authorization in project guidance. + +## Find the project context + +From the checkout root, read `.issue-spec/config.json` to find the project's Issue repository (`repo`), `profile`, `hostname`, and self-hosted `server_instance_id` when present. If the file is absent, use the project Issue target established by the task. The code remote or Source Binding can point to a different repository. + +Run `issue-spec workflow which --repo "$project_repo" --json` with the project's Issue repository. Read the config at `.workflow.source.config_path` when present, including `openspec/config.yaml` if selected. Apply the relevant project rules and load the repository-relative files in `.workflow.config.guidance.shared`. + +## Route and record + +1. Choose the destination repository by root cause. Use the project's Issue target for locally owned skills, guidance, validation, and release problems. For CLI limitations, reusable workflow improvements, or externally maintained skills, use the owning upstream Issue target identified by the task or project guidance. Set `feedback_repo` and `feedback_profile` from that destination. Keep an internal draft while the destination is uncertain. +2. Run `issue-spec --profile "$feedback_profile" auth status --json` and require `.ok` and the intended `.auth.profile`. Confirm the expected GitHub host or the self-hosted `.auth.server_instance_id` for the destination. For GitHub Enterprise with the built-in `github` profile, pass the destination's `--hostname` to auth and each Issue command as well. Use the same verified profile and repository for every destination read and write, including a retry. User or project authorization and backend permissions govern writes. +3. Search open and closed discussions for the same cause with `issue-spec --profile "$feedback_profile" search issues --repo "$feedback_repo" --scope discussion --state all --query 'specific behavior'`. Read plausible matches with `issue-spec --profile "$feedback_profile" read issue --repo "$feedback_repo" --issue N --comments`. Reuse an existing Issue for the same unresolved cause and supplement a closed decision with authorized evidence when appropriate. Link a distinct regression after a fix to its predecessor. +4. For a new authorized report, use `issue-spec --profile "$feedback_profile" issue create simple --repo "$feedback_repo" --title 'Observed problem' --body-file report.md`. Include the dated observation, originating project and revisions, expected and actual result, impact, owning layer, suggested correction and acceptance. Follow the destination's classification policy. An initial taxonomy uses `improvement/feedback` and one of `improvement/cli`, `improvement/workflow-generic`, or `improvement/workflow-project`. If classification needs a separate authorized label action, retain the original Issue identity and retry that action. +5. Record each independent event with its original context. For a skill problem, include the skill name, repository-relative path, applicable revision, and the step and impact that can be verified. Use the provider's stable source instance identifier, source repository and original task or release identifier. For a retried release, preserve its original key even when the run or attempt changes. A maintainer or configured trusted reporter can map each verifiable historical event to its own record and link the original evidence. Count independent events across Issue bodies and ordinary comments. Treat discussion, handoffs and repair verification as context for those events. +6. Preview the record. Confirm the returned `url` identifies the intended Issue and the count is correct. Omit `--dry-run` when the write is authorized. + +```sh +issue-spec --profile "$feedback_profile" feedback record --repo "$feedback_repo" --issue 42 --event-file occurrence.json --dry-run --json +``` + +```json +{ + "source_instance": "github:github.com", + "source_repository": "example/project", + "event_id": "release:v1.2.3@abc1234", + "observed_at": "2026-11-16T10:30:00+08:00", + "revision": "abc1234", + "summary": "The catalog deployment ran before publication and its download check returned HTTP 404.", + "evidence": ["https://github.com/example/project/actions/runs/123"] +} +``` + +Include only sanitized evidence. `revision` is optional. A preview reports the event key and projected confirmed count using the current identity. With a trusted reporter list, a contributor can record an event for confirmation. When the destination restricts trusted reporters, a configured reporter can confirm an earlier unconfirmed event by verifying the evidence and recording the same key. The backend supplies the comment author. A submitted field claiming confirmation or identity carries no authority. + +An ambiguous submission is reconciled by rereading the Issue. Retry the same event file if needed. If the result shows a pending label action, an authorized caller can retry that action with the same event without increasing the count. Preserve the Issue URL in handoffs. + +## Defaults and optional destination policy + +Recording and preview work after ordinary initialization. The default policy counts distinct evidence from authenticated Issue authors and suggests `priority/high` at three confirmed occurrences. + +To change the threshold or enable automatic escalation, publish a policy from an ordinary Issue in the **destination** repository. Its body contains a single JSON object, optionally fenced as JSON. To customize just the threshold, the entire body can be `{"threshold": 5}`. + +Automatic escalation uses `"mode": "auto"` and a list of trusted reporters. For each trusted account, get the stable ID from `issue-spec --profile "$feedback_profile" auth status --json` (`.auth.user_id`). Write the IDs as strings. + +```json +{ + "threshold": 3, + "mode": "auto", + "priority_label": "priority/high", + "trusted_reporter_ids": ["123"], + "higher_priority_labels": ["priority/critical"], + "hold_labels": ["priority/deferred"] +} +``` + +An automatic assignment uses a predefined repository label. The priority label defaults to `priority/high`. Higher-priority and hold labels are optional. `issue-spec/feedback-hold` and `wontfix` are recognized holds. A closed or locked Issue is ineligible. + +```sh +issue-spec --profile "$feedback_profile" feedback configure --repo "$feedback_repo" --issue 17 --dry-run --json +issue-spec --profile "$feedback_profile" feedback configure --repo "$feedback_repo" --issue 17 +``` + +Publishing requires permission to manage repository label definitions. The command binds the exact policy body to the repository's `issue-spec/feedback-policy` label definition. Change the policy Issue body and publish again to activate a new revision. Remove the policy label definition to return to the built-in suggestion policy. GitHub enforces the caller's permission to assign a label. On self-hosted, a caller who can create Issues can request promotion. The server rechecks the published policy, persisted evidence and Issue eligibility before assigning the configured label. The ordinary issue-label API uses its triage authorization. + +## Customize project guidance + +Use an entry in `guidance.shared` in the selected workflow config to customize when to use feedback, project and upstream destinations, sanitization, or standing publication authorization. The standalone feedback skill and shared reference are available after ordinary init or a workflow update. Preview an existing checkout's update with `issue-spec workflow update --dry-run --repo "$project_repo"`. + +For a requested interval review, include open and closed feedback Issues and compare their creation dates and dated evidence. Group by root cause and count distinct keys. Record the upstream fix, local adoption revision and comparable verification as they become available in relevant authorized work. Prefer the original Issue and its evidence links for handoff across sessions. diff --git a/.agents/skills/issue-spec-workflow/release.json b/.agents/skills/issue-spec-workflow/release.json index 33b7693e..fd8b1f62 100644 --- a/.agents/skills/issue-spec-workflow/release.json +++ b/.agents/skills/issue-spec-workflow/release.json @@ -3,12 +3,16 @@ "release": "development", "source_revision": "unknown", "requirements_skill_content_id": "sha256:35e55ba3b52b377acbd36ca4305cd958e3bd593008d576a7a82c9b06ab862ed1", - "content_digest": "sha256:6644c5543ea8dd9914a3c7d34da7d12f19505d1cb10e99591f7985bb8e3bff7f", + "content_digest": "sha256:cf1870225bea33dcc6a8058b06a2badab1db6a2a6dabb9b728a0c35f7f72134f", "files": [ { "path": ".agents/skills/issue-spec-apply/SKILL.md", "sha256": "2351606737a7b0201c13ecc61ce4cd652d9d4bafaa66d20abc64c51ec56b2d56" }, + { + "path": ".agents/skills/issue-spec-feedback/SKILL.md", + "sha256": "247843d9acd7ae4fe8cb72289ab357c16bd665021f86df859505f985f98a7a72" + }, { "path": ".agents/skills/issue-spec-github/SKILL.md", "sha256": "a2a1cfeb647e737f66dbbbd97a53cfc752c84395ee4f6f080d7bfab3ee48d7d5" @@ -19,7 +23,7 @@ }, { "path": ".agents/skills/issue-spec-workflow/SKILL.md", - "sha256": "bc48b5f608258aa5b821738100c68e6d2fa4d8e24aafc1ec615649482369869a" + "sha256": "e94c748d919eff7fbd11e4f9de61d8268272a733278087d1fa19cb2a58348b58" }, { "path": ".agents/skills/issue-spec-workflow/references/durable-maintenance.md", @@ -40,6 +44,10 @@ { "path": ".agents/skills/issue-spec-workflow/references/question-decisions.md", "sha256": "8c817bb08e73853101a42d8c4ca0e83e72fc81be04221f1f5004623588fa193c" + }, + { + "path": ".agents/skills/issue-spec-workflow/references/workflow-feedback.md", + "sha256": "aff8d95d905aa39c10f78a0cb605582f7d55766478b74cb42bf31f909d70e06a" } ] } diff --git a/.claude/skills/issue-spec-feedback b/.claude/skills/issue-spec-feedback new file mode 120000 index 00000000..175f9619 --- /dev/null +++ b/.claude/skills/issue-spec-feedback @@ -0,0 +1 @@ +../../.agents/skills/issue-spec-feedback \ No newline at end of file diff --git a/docs/reference.md b/docs/reference.md index 49bfc17f..ba484ab1 100644 --- a/docs/reference.md +++ b/docs/reference.md @@ -27,7 +27,7 @@ New durable specs default to `issue-spec/specs//spec.md`. If `opensp ### Shared skills and safe updates -`init` defaults to `--delivery skills`. `.agents/skills/` is canonical; Claude receives relative links per generated skill. `--delivery both|commands` remains an explicit legacy integration option. Root `AGENTS.md`/`CLAUDE.md` and project-specific skills remain project-owned. +`init` defaults to `--delivery skills`. When tool selection is omitted, skills delivery detects repository tool directories and falls back to canonical `.agents/skills` in a fresh checkout. GitHub init validates workflow inputs and checks file conflicts before saving the Issue binding and ensuring labels. Claude receives relative links when selected or detected. `--delivery both|commands` remains an explicit legacy integration option. Root `AGENTS.md`/`CLAUDE.md` and project-specific skills remain project-owned. ```yaml # issue-spec/config.yaml — optional supplements, paths relative to checkout root @@ -54,6 +54,19 @@ The preview reports paths, actions, hashes and conflicts. The apply performs the A legacy whole-directory Claude link is split while preserving previously exposed entries. Later upgrades only add generated skills, never unrelated project skills. Exact redundant Claude copies can become links; differing copies block the update. Existing worktrees retain their own committed skill version. Runtime host discovery still needs verification in a fresh session. +### Workflow feedback + +Ordinary `issue-spec init` supplies the standalone `issue-spec-feedback` skill. It can be discovered when using any project skill exposes a reproducible issue with instructions, references, or scripts. The skill shares the feedback guide with `issue-spec-workflow` and uses the existing recording and deduplication commands. The built-in policy suggests `priority/high` at three confirmed occurrences. Projects can use `guidance.shared` to refine routing and standing authorization. [Workflow feedback reference](../.agents/skills/issue-spec-workflow/references/workflow-feedback.md) + +For feedback about your own project, start with `repo` and `profile` from `.issue-spec/config.json`. Use the verified destination profile and repository in both previews and writes. + +```bash +issue-spec --profile "$feedback_profile" feedback record --repo "$feedback_repo" --issue 42 --event-file occurrence.json --dry-run --json +issue-spec --profile "$feedback_profile" feedback configure --repo "$feedback_repo" --issue 17 --dry-run --json +``` + +Omit `--dry-run` for authorized writes. Use `feedback configure` when the destination wants a custom threshold or automatic escalation. GitHub checks label permission. On self-hosted, the updated Server checks Issue creation permission and validates eligibility from stored evidence. + ### HTML review authoring HTML review authoring is enabled by default. To keep Proposal, Design, and Implement authoring on the typed Markdown workflow without loading or generating human-review projection instructions, configure the required boolean explicitly: diff --git a/docs/reference.zh-CN.md b/docs/reference.zh-CN.md index ebdbec3b..3002598c 100644 --- a/docs/reference.zh-CN.md +++ b/docs/reference.zh-CN.md @@ -25,6 +25,19 @@ issue-spec workflow which --repo owner/repo --json 新的长期 spec 默认写入 `issue-spec/specs//spec.md`。若 `openspec/specs//spec.md` 已存在,`durable-spec` 可以更新那个遗留的长期 spec,并报告所选的兼容路径。 +### 工作流反馈 + +常规 `issue-spec init` 默认生成独立的 `issue-spec-feedback` 技能。使用任意项目技能时遇到可复核的指令、引用或脚本问题,都能通过它找到反馈入口。它和 `issue-spec-workflow` 共用指引,沿用现有记录、去重和计数命令。默认累计三次确认复现时建议标记 `priority/high`。项目可通过 `guidance.shared` 定制上报去向和授权范围。 [反馈指引与配置示例](../.agents/skills/issue-spec-workflow/references/workflow-feedback.md) + +反馈本项目的问题时,先读取 `.issue-spec/config.json` 中的 `repo` 和 `profile`。预览和写入都使用核验后的目标仓库和 profile。 + +```bash +issue-spec --profile "$feedback_profile" feedback record --repo "$feedback_repo" --issue 42 --event-file occurrence.json --dry-run --json +issue-spec --profile "$feedback_profile" feedback configure --repo "$feedback_repo" --issue 17 --dry-run --json +``` + +在授权写入时去掉 `--dry-run`。自定义阈值或开启自动升级时,由目标仓库维护者运行 `feedback configure`。GitHub 按标签权限校验。自托管由新版 Server 校验 Issue 创建权限,并根据已保存证据判断能否升级。 + ### HTML review 创作指引 HTML review 创作指引默认启用。若要让 Proposal、Design 与 Implement 创作只使用类型化 Markdown 工作流,而不加载或生成面向人工 review 的 projection 指令,请显式配置这个必填布尔值: @@ -76,7 +89,7 @@ rules: ### 共享技能、项目补充与安全升级 -`init` 默认 `--delivery skills`。通用技能保存在 `.agents/skills/`,Claude 按技能目录使用相对软链。`--delivery both|commands` 仅在显式选择时生成旧命令。项目维护 `AGENTS.md`、`CLAUDE.md`、自有技能与补充规则。 +`init` 默认 `--delivery skills`。省略 `--tools` 时按仓库已有目录探测宿主,空仓库默认生成 `.agents/skills`。GitHub 初始化会在保存 Issue 绑定和设置标签前校验工作流配置及文件冲突。显式选择或探测到 Claude 时按技能目录生成相对软链。`--delivery both|commands` 仅在显式选择时生成旧命令。项目维护 `AGENTS.md`、`CLAUDE.md`、自有技能与补充规则。 ```yaml # issue-spec/config.yaml,路径相对于仓库根目录 diff --git a/internal/auth/auth.go b/internal/auth/auth.go index f74388d0..0fa2e694 100644 --- a/internal/auth/auth.go +++ b/internal/auth/auth.go @@ -37,6 +37,7 @@ type Token struct { Value string `json:"-"` Source string `json:"source"` User string `json:"user,omitempty"` + UserID int64 `json:"user_id,string,omitempty"` Scopes []string `json:"scopes,omitempty"` Host string `json:"host"` Profile string `json:"profile,omitempty"` diff --git a/internal/commands/auth.go b/internal/commands/auth.go index 588aa166..99e60184 100644 --- a/internal/commands/auth.go +++ b/internal/commands/auth.go @@ -57,6 +57,7 @@ func (a *app) runAuthStatus(ctx context.Context, args []string) int { return 1 } token.User = user.Login + token.UserID = user.ID token.Scopes = scopes if *jsonOut { return a.outputJSON(map[string]any{"ok": true, "auth": token, "backend": token.Backend}) diff --git a/internal/commands/commands.go b/internal/commands/commands.go index f612ae87..60d8a8fb 100644 --- a/internal/commands/commands.go +++ b/internal/commands/commands.go @@ -91,6 +91,8 @@ func Execute(args []string, in io.Reader, out io.Writer, errOut io.Writer) int { return a.runIssue(ctx, args[1:]) case "comment": return a.runComment(ctx, args[1:]) + case "feedback": + return a.runFeedback(ctx, args[1:]) case "question": return a.runQuestion(ctx, args[1:]) case "projection": @@ -223,6 +225,8 @@ Usage: issue-spec comment create --repo owner/repo --issue N --body-file reply.md [--json] issue-spec comment edit --repo owner/repo --comment-id N --body-file reply.md [--json] issue-spec comment delete --repo owner/repo --comment-id N [--json] + issue-spec feedback configure --repo owner/repo --issue N [--dry-run] [--json] + issue-spec feedback record --repo owner/repo --issue N --event-file event.json [--dry-run] [--json] issue-spec comment generate --type SPEC --id SPEC-1001 --input-file spec.json [--status confirmed] [--scope "..."] issue-spec comment generate --type SPEC|TASK --example issue-spec comment upsert --repo owner/repo --issue 1 --type SPEC --id SPEC-1001 --body-file file.md [--allow-noncanonical] diff --git a/internal/commands/feedback.go b/internal/commands/feedback.go new file mode 100644 index 00000000..4f1f69a4 --- /dev/null +++ b/internal/commands/feedback.go @@ -0,0 +1,101 @@ +package commands + +import ( + "context" + "fmt" + + "github.com/higress-group/issue-spec/internal/auth" + "github.com/higress-group/issue-spec/internal/feedback" +) + +func (a *app) runFeedback(ctx context.Context, args []string) int { + if len(args) == 0 || isHelpArg(args[0]) { + fmt.Fprintln(a.out, "Usage: issue-spec feedback configure|record [options]") + return 0 + } + action := args[0] + if action != "configure" && action != "record" { + a.errorf("unknown feedback command %q\n", action) + return 2 + } + + fs := newFlagSet("feedback "+action, a.err) + repoFlag := fs.String("repo", "", "target Issue repository owner/name") + host := fs.String("hostname", "github.com", "issue backend hostname") + issue := fs.Int("issue", 0, "positive Issue number in the selected repository") + dryRun := fs.Bool("dry-run", false, "preview using read-only backend operations") + jsonOut := fs.Bool("json", false, "write JSON output") + var eventFile *string + if action == "record" { + eventFile = fs.String("event-file", "", "JSON occurrence file, or - for stdin") + } + if ok, code := a.parseFlagSet(fs, args[1:]); !ok { + return code + } + repo, ok := a.validateRepo(*repoFlag) + if !ok { + return 2 + } + if *issue <= 0 { + a.errorf("--issue must be a positive Issue number in the selected repository\n") + return 2 + } + var event feedback.Event + if eventFile != nil { + input, ok := a.readFlagFile(*eventFile, "event-file") + if !ok { + return 2 + } + parsed, err := feedback.ParseEvent(input) + if err != nil { + a.errorf("%v\n", err) + return 2 + } + event = parsed + } + + client, token, err := a.clientFor(ctx, *host) + if err != nil { + a.errorf("select feedback Issue backend: %v\n", err) + return 1 + } + backend, ok := client.(feedback.Backend) + if !ok { + a.errorf("the selected Issue backend does not support feedback label operations\n") + return 1 + } + if action == "configure" { + result, err := feedback.Configure(ctx, backend, repo, *issue, *dryRun) + if err != nil { + a.errorf("%v\n", err) + return 1 + } + if *jsonOut { + return a.outputJSON(result) + } + status := "published" + if *dryRun { + status = "preview" + } + fmt.Fprintf(a.out, "%s %s feedback policy from Issue #%d (%s, threshold %d)\n", + status, repo, *issue, result.Policy.Mode, result.Policy.Threshold) + return 0 + } + + result, err := feedback.Record(ctx, backend, repo, *issue, event, feedback.RecordOptions{ + DryRun: *dryRun, SelfHosted: token.ProfileKind == string(auth.ProfileKindHosted), + }) + if err != nil { + a.errorf("%v\n", err) + return 1 + } + if *jsonOut { + return a.outputJSON(result) + } + fmt.Fprintf(a.out, "%s %s#%d %s\n%d confirmed occurrences, promotion %s (%s)\n", + result.EventStatus, repo, *issue, result.EventKey, result.ConfirmedCount, result.Promotion.Status, result.Promotion.Label) + if result.Promotion.Reason != "" { + fmt.Fprintln(a.out, result.Promotion.Reason) + } + return 0 +} diff --git a/internal/commands/init.go b/internal/commands/init.go index 6551c982..5307a441 100644 --- a/internal/commands/init.go +++ b/internal/commands/init.go @@ -1,6 +1,7 @@ package commands import ( + "bytes" "context" "encoding/json" "errors" @@ -12,10 +13,12 @@ import ( "github.com/higress-group/issue-spec/internal/auth" "github.com/higress-group/issue-spec/internal/github" + "github.com/higress-group/issue-spec/internal/workflow" "gopkg.in/yaml.v3" ) const workflowNeutralLanguageGuidance = "configure rules.language in the selected project workflow; for legacy OpenSpec, use openspec/config.yaml" +const workflowLanguageConfigPath = "issue-spec/config.yaml" func (a *app) runInit(ctx context.Context, args []string) int { fs := newFlagSet("init", a.err) @@ -89,6 +92,14 @@ func (a *app) runInit(ctx context.Context, args []string) int { if !ok { return 2 } + var workflowPlan initWorkflowPlan + if !workflowNeutral { + workflowPlan, err = planGitHubInitWorkflow(".", *repoFlag, *tools, *delivery, *language) + if err != nil { + a.errorf("validate init workflow: %v\n", err) + return 1 + } + } client, token, err := a.clientFor(ctx, *host) if err != nil { a.errorf("auth required for init on %s: %v\n", auth.NormalizeHost(*host), err) @@ -126,11 +137,19 @@ func (a *app) runInit(ctx context.Context, args []string) int { } } - languageRequested := strings.TrimSpace(*language) != "" var languageConfigPath string - if languageRequested && !workflowNeutral { - languageConfigPath, err = writeWorkflowLanguageConfig(".", *language) + if workflowPlan.languageConfig != nil { + languageConfigPath = workflowLanguageConfigPath + current, err := renderWorkflowLanguageConfig(languageConfigPath, *language) if err != nil { + a.errorf("check planned workflow language config: %v\n", err) + return 1 + } + if !bytes.Equal(current, workflowPlan.languageConfig) { + a.errorf("%s changed after workflow preflight\n", languageConfigPath) + return 1 + } + if err := writeTextFile(languageConfigPath, string(workflowPlan.languageConfig)); err != nil { a.errorf("write workflow language config: %v\n", err) return 1 } @@ -138,7 +157,7 @@ func (a *app) runInit(ctx context.Context, args []string) int { workflows := workflowGenerationResult{Delivery: *delivery} if !workflowNeutral { - workflows, err = writeWorkflowArtifacts(".", *repoFlag, *tools, *delivery) + workflows, err = installWorkflowArtifacts(".", workflowPlan.update) if err != nil { a.errorf("generate workflow artifacts: %v\n", err) return 1 @@ -149,6 +168,7 @@ func (a *app) runInit(ctx context.Context, args []string) int { } } + languageRequested := strings.TrimSpace(*language) != "" result := map[string]any{"ok": true, "repo": *repoFlag, "hostname": token.Host, "auth": token, "backend": token.Backend, "config": configPath, "labels": labels, "workflows": workflows} if languageConfigPath != "" { result["language"] = languageDisplay(*language) @@ -185,6 +205,38 @@ func (a *app) runInit(ctx context.Context, args []string) int { return 0 } +type initWorkflowPlan struct { + update workflowUpdatePlan + languageConfig []byte +} + +func planGitHubInitWorkflow(root, repo, toolsArg, delivery, language string) (initWorkflowPlan, error) { + var result initWorkflowPlan + delivery, tools, err := resolveWorkflowGenerationOptions(root, toolsArg, delivery) + if err != nil { + return result, err + } + result.update.Generation.Delivery = delivery + if strings.TrimSpace(language) != "" { + result.languageConfig, err = renderWorkflowLanguageConfig(filepath.Join(root, workflowLanguageConfigPath), language) + if err != nil { + return result, err + } + } + if len(tools) == 0 { + return result, nil + } + plan, err := workflow.ResolveWithOptions(workflow.ResolveOptions{Root: root, IssueSpecConfig: result.languageConfig}) + if err != nil { + return result, err + } + result.update, err = planWorkflowUpdate(root, repo, delivery, tools, plan, nil) + if err != nil { + return result, err + } + return result, result.update.conflictError() +} + func resolveGlobalPromptInstallOptions(install bool, directory string, dryRun bool, delivery string) (globalPromptInstallOptions, error) { options := globalPromptInstallOptions{ Enabled: install || strings.TrimSpace(directory) != "" || dryRun, @@ -243,19 +295,30 @@ func (a *app) printWorkflowGeneration(workflows workflowGenerationResult) { // generated workflow artifacts instruct agents to author natural-language content // in the requested language while keeping canonical structural tokens in English. func writeWorkflowLanguageConfig(root, language string) (string, error) { + path := filepath.Join(root, workflowLanguageConfigPath) + out, err := renderWorkflowLanguageConfig(path, language) + if err != nil { + return "", err + } + if err := writeTextFile(path, string(out)); err != nil { + return "", err + } + return filepath.ToSlash(path), nil +} + +func renderWorkflowLanguageConfig(path, language string) ([]byte, error) { display := languageDisplay(language) - path := filepath.Join(root, "issue-spec", "config.yaml") cfg := map[string]any{} if data, err := os.ReadFile(path); err == nil { if err := yaml.Unmarshal(data, &cfg); err != nil { - return "", fmt.Errorf("parse existing %s: %w", filepath.ToSlash(path), err) + return nil, fmt.Errorf("parse existing %s: %w", filepath.ToSlash(path), err) } if cfg == nil { cfg = map[string]any{} } } else if !errors.Is(err, os.ErrNotExist) { - return "", err + return nil, err } rules, _ := cfg["rules"].(map[string]any) @@ -270,17 +333,7 @@ func writeWorkflowLanguageConfig(root, language string) (string, error) { rules["language_instructions"] = fmt.Sprintf("Write natural-language body content (descriptions, rationale, design notes, questions, decisions, task descriptions, and QUESTION/scenario prose) in %[1]s. %[2]s Ordinary (non-staged) issue titles use a descriptive %[1]s title. Keep canonical structural tokens in English so validation passes: the `## Requirement:` and `### Scenario:` headings, the `**WHEN**`/`**THEN**` scenario bullets, the MUST/SHALL normative keywords, and typed comment headers.", display, stagedTitleInstructions) cfg["rules"] = rules - out, err := yaml.Marshal(cfg) - if err != nil { - return "", err - } - if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil { - return "", err - } - if err := os.WriteFile(path, out, 0o644); err != nil { - return "", err - } - return filepath.ToSlash(path), nil + return yaml.Marshal(cfg) } // languageDisplay maps common language codes to a descriptive label while diff --git a/internal/commands/init_feedback_test.go b/internal/commands/init_feedback_test.go new file mode 100644 index 00000000..3e0b3bbc --- /dev/null +++ b/internal/commands/init_feedback_test.go @@ -0,0 +1,233 @@ +package commands + +import ( + "bytes" + "context" + "encoding/json" + "fmt" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "strings" + "sync/atomic" + "testing" + + "github.com/higress-group/issue-spec/internal/auth" + "github.com/higress-group/issue-spec/internal/feedback" + "github.com/higress-group/issue-spec/internal/github" +) + +func TestInitInstallsStandaloneFeedbackSkillByDefault(t *testing.T) { + for _, tc := range []struct { + name string + skill string + claude bool + }{ + {name: "fresh repository"}, + {name: "existing Codex skill", skill: ".agents/skills/local-check/SKILL.md"}, + {name: "existing Claude skill", skill: ".claude/skills/local-check/SKILL.md", claude: true}, + } { + t.Run(tc.name, func(t *testing.T) { + t.Chdir(t.TempDir()) + const instructions = "# Project instructions\n\nUse the project check skill.\n" + const projectSkill = "---\nname: local-check\ndescription: Run project checks.\n---\n\nRun the project checks.\n" + writeWorkflowTestFile(t, "AGENTS.md", instructions) + if tc.skill != "" { + writeWorkflowTestFile(t, tc.skill, projectSkill) + } + + var out, errOut bytes.Buffer + app := newInitTestApp(t, &out, &errOut) + if code := app.runInit(t.Context(), []string{"--repo", "acme/widgets"}); code != 0 { + t.Fatalf("init exit = %d, stderr=%q", code, errOut.String()) + } + + const entry = ".agents/skills/issue-spec-feedback/SKILL.md" + const guide = "../issue-spec-workflow/references/workflow-feedback.md" + feedback := readTestFile(t, entry) + if !strings.Contains(feedback, "name: issue-spec-feedback\n") || !strings.Contains(feedback, "("+guide+")") { + t.Fatalf("feedback skill is missing its discoverable name or shared guide:\n%s", feedback) + } + if guideBody := readTestFile(t, filepath.Join(filepath.Dir(entry), guide)); !strings.Contains(guideBody, " feedback record ") { + t.Fatal("the shared guide did not lead to feedback record") + } + workflow := readTestFile(t, ".agents/skills/issue-spec-workflow/SKILL.md") + if !strings.Contains(workflow, "(references/workflow-feedback.md)") { + t.Fatal("workflow and standalone feedback must use the same guide") + } + + claudePath := filepath.Join(".claude", "skills", "issue-spec-feedback") + if tc.claude { + if link, err := os.Readlink(claudePath); err != nil || link != "../../.agents/skills/issue-spec-feedback" { + t.Fatalf("Claude feedback link = %q, err=%v", link, err) + } + if got := readTestFile(t, filepath.Join(claudePath, "SKILL.md")); got != feedback { + t.Fatal("Claude resolved a different feedback skill") + } + readTestFile(t, filepath.Join(claudePath, guide)) + } else if _, err := os.Lstat(claudePath); !os.IsNotExist(err) { + t.Fatalf("unexpected Claude feedback exposure: %v", err) + } + if got := readTestFile(t, "AGENTS.md"); got != instructions { + t.Fatal("init modified project-owned instructions") + } + if tc.skill != "" && readTestFile(t, tc.skill) != projectSkill { + t.Fatal("init modified a project-owned skill") + } + if _, err := os.Stat("issue-spec/config.yaml"); !os.IsNotExist(err) { + t.Fatalf("default skill discovery required workflow configuration: %v", err) + } + }) + } +} + +func TestGitHubInitRejectsInvalidWorkflowBeforeWrites(t *testing.T) { + const bindingPath = ".issue-spec/config.json" + const binding = `{"version":1,"repo":"acme/previous","profile":"github","hostname":"github.com"}` + const feedbackPath = ".agents/skills/issue-spec-feedback/SKILL.md" + for _, tc := range []struct { + name string + path string + body string + args []string + err string + }{ + {name: "malformed workflow without detected tools", path: "issue-spec/config.yaml", body: "rules: [", err: "yaml:"}, + {name: "project-owned skill collision", path: feedbackPath, body: "Project-owned feedback.", args: []string{"--language", "zh"}, err: "locally changed or not managed"}, + } { + t.Run(tc.name, func(t *testing.T) { + t.Chdir(t.TempDir()) + writeWorkflowTestFile(t, bindingPath, binding) + writeWorkflowTestFile(t, tc.path, tc.body) + var out, errOut bytes.Buffer + app := newInitTestApp(t, &out, &errOut) + labelWrites := 0 + app.newGitHubBackend = func(_ context.Context, selection auth.GitHubBackendSelection) (github.Backend, error) { + return fakeGitHubBackend{ + info: github.BackendInfo{Name: selection.Name, Kind: selection.Kind, Host: selection.Host}, + user: github.User{Login: "octocat"}, + createLabel: func(_ context.Context, _ string, name, _, _ string) (github.LabelResult, error) { + labelWrites++ + return github.LabelResult{Name: name, Created: true}, nil + }, + }, nil + } + + args := append([]string{"--repo", "acme/widgets"}, tc.args...) + if code := app.runInit(t.Context(), args); code == 0 || !strings.Contains(errOut.String(), tc.err) { + t.Fatalf("init exit = %d, stderr=%q", code, errOut.String()) + } + if got := readTestFile(t, bindingPath); got != binding || labelWrites != 0 { + t.Fatalf("failed init changed binding to %q and attempted %d label writes", got, labelWrites) + } + if got := readTestFile(t, tc.path); got != tc.body { + t.Fatalf("failed init changed project file to %q", got) + } + for _, path := range []string{"issue-spec/config.yaml", feedbackPath, workflowManifestPath} { + if path == tc.path { + continue + } + if _, err := os.Lstat(path); !os.IsNotExist(err) { + t.Fatalf("failed init created %s: %v", path, err) + } + } + }) + } +} + +func TestGeneratedFeedbackPreviewUsesBoundProfile(t *testing.T) { + const repo = "acme/widgets" + occurrence := readTestFile(t, "../../testdata/workflow-feedback/release-0.6.3.json") + for _, tc := range []struct { + kind auth.ProfileKind + profile string + }{ + {kind: auth.ProfileKindGitHub, profile: "github"}, + {kind: auth.ProfileKindHosted, profile: "team"}, + } { + t.Run(string(tc.kind), func(t *testing.T) { + clearCommandAuthEnv(t) + t.Setenv(auth.GitHubBackendEnv, "rest") + t.Setenv(auth.ProfileEnv, "") + t.Setenv("ISSUE_SPEC_TOKEN", "test-reporter") + t.Chdir(t.TempDir()) + if err := os.Mkdir(".git", 0o755); err != nil { + t.Fatal(err) + } + + target, _ := newFeedbackTestServer(t) + other, otherRequests := newFeedbackTestServer(t) + profile := auth.Profile{Name: tc.profile, Kind: tc.kind, Hostname: "github.com", + APIURL: target.URL, NativeAPIURL: target.URL + "/api/v1", WebURL: target.URL, ServerInstanceID: "intended"} + if err := auth.SaveProfile(profile, false); err != nil { + t.Fatal(err) + } + if err := auth.SaveProfile(auth.Profile{Name: "other", Kind: auth.ProfileKindHosted, + APIURL: other.URL, NativeAPIURL: other.URL + "/api/v1", WebURL: other.URL, ServerInstanceID: "other"}, true); err != nil { + t.Fatal(err) + } + if tc.kind == auth.ProfileKindGitHub { + // An explicitly active profile also takes precedence over the GitHub checkout marker. + t.Setenv(auth.ProfileEnv, "other") + } + writeWorkflowTestFile(t, ".issue-spec/config.json", fmt.Sprintf(`{"repo":%q,"profile":%q,"hostname":"github.com"}`, repo, profile.Name)) + writeWorkflowTestFile(t, "occurrence.json", occurrence) + if _, err := writeWorkflowArtifacts(".", repo, "", workflowDeliverySkills); err != nil { + t.Fatal(err) + } + guide := readTestFile(t, ".agents/skills/issue-spec-workflow/references/workflow-feedback.md") + var args []string + for line := range strings.Lines(guide) { + if strings.HasPrefix(line, "issue-spec ") && strings.Contains(line, " feedback record ") { + resolved := strings.NewReplacer(`"$feedback_profile"`, profile.Name, `"$feedback_repo"`, repo) + args = strings.Fields(resolved.Replace(line))[1:] + break + } + } + if len(args) == 0 { + t.Fatal("the shared guide has no feedback preview example") + } + var out, errOut bytes.Buffer + if code := Execute(args, strings.NewReader(""), &out, &errOut); code != 0 { + t.Fatalf("feedback preview exit = %d, stderr=%q", code, errOut.String()) + } + var result feedback.Result + if err := json.Unmarshal(out.Bytes(), &result); err != nil { + t.Fatal(err) + } + if result.URL != target.URL+"/acme/widgets/issues/42" || otherRequests.Load() != 0 || + !result.DryRun || result.EventStatus != "would_record" || result.ConfirmedCount != 1 { + t.Fatalf("feedback preview = %+v, requests to global profile = %d", result, otherRequests.Load()) + } + }) + } +} + +func newFeedbackTestServer(t *testing.T) (*httptest.Server, *atomic.Int32) { + t.Helper() + var requests atomic.Int32 + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + requests.Add(1) + if r.Method != http.MethodGet { + t.Errorf("feedback preview attempted %s %s", r.Method, r.URL.Path) + w.WriteHeader(http.StatusMethodNotAllowed) + return + } + switch r.URL.Path { + case "/user": + writeTestJSON(w, github.User{ID: 7, Login: "reporter"}) + case "/repos/acme/widgets/issues/42": + writeTestJSON(w, github.Issue{Number: 42, State: "open", HTMLURL: "http://" + r.Host + "/acme/widgets/issues/42"}) + case "/repos/acme/widgets/issues/42/comments": + writeTestJSON(w, []github.Comment{}) + case "/repos/acme/widgets/labels/issue-spec/feedback-policy": + http.NotFound(w, r) + default: + t.Errorf("unexpected request %s", r.URL.Path) + http.NotFound(w, r) + } + })) + t.Cleanup(server.Close) + return server, &requests +} diff --git a/internal/commands/init_language_test.go b/internal/commands/init_language_test.go index 7b99adb9..e0256660 100644 --- a/internal/commands/init_language_test.go +++ b/internal/commands/init_language_test.go @@ -178,6 +178,24 @@ func TestInitWithoutLanguageDoesNotWriteWorkflowConfig(t *testing.T) { } } +func TestInitLanguagePreflightsTheNewConfigInsteadOfLegacy(t *testing.T) { + t.Chdir(t.TempDir()) + const legacy = "schema: missing-legacy-schema\n" + writeWorkflowTestFile(t, "openspec/config.yaml", legacy) + var out, errOut bytes.Buffer + app := newInitTestApp(t, &out, &errOut) + if code := app.runInit(t.Context(), []string{"--repo", "acme/widgets", "--language", "zh"}); code != 0 { + t.Fatalf("init exit=%d stderr=%q", code, errOut.String()) + } + if got := readTestFile(t, "openspec/config.yaml"); got != legacy { + t.Fatalf("init changed the legacy config: %q", got) + } + skill := readTestFile(t, ".agents/skills/issue-spec-workflow/SKILL.md") + if !strings.Contains(skill, "- Workflow Config: `issue-spec/config.yaml`") { + t.Fatalf("the generated skills did not use the planned config:\n%s", skill) + } +} + func TestInitToolsNoneReportsLanguageWithoutWorkflowWrites(t *testing.T) { for _, jsonOutput := range []bool{false, true} { name := "text" diff --git a/internal/commands/init_self_hosted_test.go b/internal/commands/init_self_hosted_test.go index 83c7df59..ce6d3ca7 100644 --- a/internal/commands/init_self_hosted_test.go +++ b/internal/commands/init_self_hosted_test.go @@ -584,7 +584,7 @@ func TestSelfHostedInitEnsuresRepositoryBindingAndResumesIdempotently(t *testing journalBefore := readTestFile(t, filepath.Join(root, ".issue-spec", "init-state.json")) remoteCallsBefore := [3]int{ensureCalls, bindingCalls, labelCalls} noProviderArgs := []string{"--repo", "local-source/local-checkout", "--server-org", "browser-e2e", "--server-repo", "httpbin", - "--skip-source-binding", "--skip-labels", "--tools", "codex", "--delivery", "skills", "--json"} + "--skip-source-binding", "--skip-labels", "--json"} { var out, errOut bytes.Buffer app := newApp(strings.NewReader(""), &out, &errOut) @@ -616,6 +616,10 @@ func TestSelfHostedInitEnsuresRepositoryBindingAndResumesIdempotently(t *testing t.Fatalf("provider-neutral rerun exit=%d stderr=%s stdout=%s", code, errOut.String(), out.String()) } } + feedbackSkill := readTestFile(t, filepath.Join(root, ".agents", "skills", "issue-spec-feedback", "SKILL.md")) + if !strings.Contains(feedbackSkill, "../issue-spec-workflow/references/workflow-feedback.md") { + t.Fatalf("default self-hosted init did not link the shared feedback guide:\n%s", feedbackSkill) + } preservedConfig := readTestFile(t, filepath.Join(root, ".issue-spec", "config.json")) for _, want := range []string{`"key": "code.example"`, `"external_repository": "acme/widgets"`, `"change.create"`, `"change.comment"`} { if !strings.Contains(preservedConfig, want) { diff --git a/internal/commands/workflow_install.go b/internal/commands/workflow_install.go index 6e17ac17..7372bfa0 100644 --- a/internal/commands/workflow_install.go +++ b/internal/commands/workflow_install.go @@ -29,6 +29,13 @@ type workflowUpdatePlan struct { Generation workflowGenerationResult `json:"generation"` } +func (p workflowUpdatePlan) conflictError() error { + if len(p.Conflicts) > 0 { + return fmt.Errorf("workflow update conflicts:\n%s", strings.Join(p.Conflicts, "\n")) + } + return nil +} + const workflowManifestPath = ".agents/skills/issue-spec-workflow/release.json" func workflowHash(body []byte) string { return fmt.Sprintf("%x", sha256.Sum256(body)) } @@ -311,8 +318,8 @@ func planClaudeSkillLinks(root, stage string, update *workflowUpdatePlan) error // Move each replaced entry into a sibling backup before installing it. A failed // write rolls back all completed moves, including directory/link migrations. func applyWorkflowUpdate(root string, update workflowUpdatePlan) (err error) { - if len(update.Conflicts) > 0 { - return fmt.Errorf("workflow update conflicts:\n%s", strings.Join(update.Conflicts, "\n")) + if err := update.conflictError(); err != nil { + return err } if len(update.Changes) == 0 { return nil @@ -412,7 +419,11 @@ func writeWorkflowArtifactsResolvedWithProvider(root, repo, delivery string, too if err != nil { return update.Generation, err } - if err = applyWorkflowUpdate(root, update); err != nil { + return installWorkflowArtifacts(root, update) +} + +func installWorkflowArtifacts(root string, update workflowUpdatePlan) (workflowGenerationResult, error) { + if err := applyWorkflowUpdate(root, update); err != nil { return update.Generation, err } for _, change := range update.Changes { diff --git a/internal/commands/workflows.go b/internal/commands/workflows.go index b4b7cb7e..34b5ac1a 100644 --- a/internal/commands/workflows.go +++ b/internal/commands/workflows.go @@ -69,8 +69,10 @@ type globalPromptInstallOptions struct { DryRun bool } +var codexWorkflowTool = workflowTool{ID: "codex", RootDir: ".agents"} + var workflowTools = []workflowTool{ - {ID: "codex", RootDir: ".agents"}, + codexWorkflowTool, {ID: "claude", RootDir: ".claude"}, } @@ -451,6 +453,9 @@ func resolveWorkflowGenerationOptions(root, toolsArg, delivery string) (string, if err != nil { return "", nil, err } + if len(tools) == 0 && strings.TrimSpace(toolsArg) == "" && delivery == workflowDeliverySkills { + tools = []workflowTool{codexWorkflowTool} + } return delivery, tools, nil } @@ -461,21 +466,18 @@ func workflowSkills(repo string, plan workflow.Plan) []templates.RenderedSkill { func workflowSkillsWithProvider(repo string, plan workflow.Plan, provider *workflow.ProviderPlan) []templates.RenderedSkill { options := templates.WorkflowAuthoringOptions{HTMLReviewEnabled: plan.HTMLReviewEnabled()} skills := templates.IssueSpecSkillsWithOptions(repo, options) - notice := workflowNotice(plan) + notice := strings.TrimRight(workflowNotice(plan), "\n") + if provider != nil { + notice += "\n\n" + strings.TrimRight(templates.ProviderWorkflowNotice(*provider), "\n") + } for i := range skills { - if skills[i].Name == "issue-spec-github" { + switch skills[i].Name { + case "issue-spec-feedback", "issue-spec-github": continue } - skills[i].Content = strings.TrimRight(skills[i].Content, "\n") + "\n\n" + strings.TrimRight(notice, "\n") + "\n" + skills[i].Content = strings.TrimRight(skills[i].Content, "\n") + "\n\n" + notice + "\n" } if provider != nil { - providerNotice := templates.ProviderWorkflowNotice(*provider) - for i := range skills { - if skills[i].Name == "issue-spec-github" { - continue - } - skills[i].Content = strings.TrimRight(skills[i].Content, "\n") + "\n\n" + strings.TrimRight(providerNotice, "\n") + "\n" - } skills = append(skills, templates.IssueSpecProviderSkill(repo, *provider)) } return skills diff --git a/internal/commands/workflows_test.go b/internal/commands/workflows_test.go index d87fb8b7..f54b7174 100644 --- a/internal/commands/workflows_test.go +++ b/internal/commands/workflows_test.go @@ -29,13 +29,13 @@ func TestWriteWorkflowArtifactsUsesCurrentCodexSkillPathWithoutGlobalWrites(t *t if err != nil { t.Fatal(err) } - if got, want := len(result.SkillFiles), 4; got != want { + if got, want := len(result.SkillFiles), 5; got != want { t.Fatalf("skill file count = %d, want %d", got, want) } - if got, want := len(result.SkillResourceFiles), len(templates.HumanReviewProjectionResources())+6; got != want { + if got, want := len(result.SkillResourceFiles), len(templates.HumanReviewProjectionResources())+7; got != want { t.Fatalf("skill resource file count = %d, want %d", got, want) } - if got, want := len(result.SkillLinks), 4; got != want { + if got, want := len(result.SkillLinks), 5; got != want { t.Fatalf("skill links = %v, want %v", got, want) } if got, want := len(result.CommandFiles), 2; got != want { @@ -412,11 +412,13 @@ func TestCheckedInWorkflowArtifactsExactlyMatchGenerator(t *testing.T) { for _, relative := range append( []string{ filepath.Join(".agents", "skills", "issue-spec-apply", "SKILL.md"), + filepath.Join(".agents", "skills", "issue-spec-feedback", "SKILL.md"), filepath.Join(".agents", "skills", "issue-spec-github", "SKILL.md"), filepath.Join(".agents", "skills", "issue-spec-propose", "SKILL.md"), filepath.Join(".agents", "skills", "issue-spec-workflow", "SKILL.md"), filepath.Join(".agents", "skills", "issue-spec-workflow", "release.json"), filepath.Join(".claude", "skills", "issue-spec-apply", "SKILL.md"), + filepath.Join(".claude", "skills", "issue-spec-feedback", "SKILL.md"), filepath.Join(".claude", "skills", "issue-spec-github", "SKILL.md"), filepath.Join(".claude", "skills", "issue-spec-propose", "SKILL.md"), filepath.Join(".claude", "skills", "issue-spec-workflow", "SKILL.md"), diff --git a/internal/feedback/event.go b/internal/feedback/event.go new file mode 100644 index 00000000..bfd16079 --- /dev/null +++ b/internal/feedback/event.go @@ -0,0 +1,106 @@ +package feedback + +import ( + "encoding/json" + "fmt" + "html" + "io" + "net/url" + "regexp" + "strings" + "time" +) + +const OccurrencePrefix = "" + +var ( + instancePattern = regexp.MustCompile(`^[a-z0-9][a-z0-9._:-]{0,159}$`) + repositoryPattern = regexp.MustCompile(`^[a-z0-9._-]+/[a-z0-9._-]+$`) + eventIDPattern = regexp.MustCompile(`^[A-Za-z0-9][A-Za-z0-9._:/@-]{0,191}$`) +) + +type Event struct { + SourceInstance string `json:"source_instance"` + SourceRepository string `json:"source_repository"` + EventID string `json:"event_id"` + ObservedAt time.Time `json:"observed_at"` + Revision string `json:"revision,omitempty"` + Summary string `json:"summary"` + Evidence []string `json:"evidence"` +} + +func ParseEvent(input string) (Event, error) { + var event Event + if err := decodeJSON(input, &event); err != nil { + return Event{}, fmt.Errorf("decode feedback event: %w", err) + } + event.SourceInstance = strings.ToLower(strings.TrimSpace(event.SourceInstance)) + event.SourceRepository = strings.ToLower(strings.TrimSpace(event.SourceRepository)) + event.EventID = strings.TrimSpace(event.EventID) + event.Summary = strings.TrimSpace(event.Summary) + event.Revision = strings.TrimSpace(event.Revision) + if !instancePattern.MatchString(event.SourceInstance) || !repositoryPattern.MatchString(event.SourceRepository) { + return Event{}, fmt.Errorf("provide the source instance and repository in owner/name form") + } + if !eventIDPattern.MatchString(event.EventID) { + return Event{}, fmt.Errorf("provide a stable event_id of up to 192 letters, digits or ._:/@- characters") + } + if event.ObservedAt.IsZero() || event.Summary == "" || len(event.Evidence) == 0 { + return Event{}, fmt.Errorf("observed_at, summary and at least one evidence link are required") + } + for _, link := range event.Evidence { + u, err := url.Parse(link) + if err != nil || u.Host == "" || u.User != nil || (u.Scheme != "https" && u.Scheme != "http") { + return Event{}, fmt.Errorf("evidence links must be HTTP or HTTPS URLs without user information") + } + } + return event, nil +} + +func (e Event) Key() string { + return e.SourceInstance + "/" + e.SourceRepository + "/" + e.EventID +} + +func (e Event) commentBody() (string, error) { + data, err := json.Marshal(e) + if err != nil { + return "", err + } + var body strings.Builder + fmt.Fprintf(&body, "%s%s%s\n\n### Workflow feedback occurrence\n\n", OccurrencePrefix, data, occurrenceSuffix) + fmt.Fprintf(&body, "%s\n\n- Observed %s\n- Source %s\n", html.EscapeString(e.Summary), e.ObservedAt.Format(time.RFC3339), e.Key()) + if e.Revision != "" { + fmt.Fprintf(&body, "- Revision %s\n", html.EscapeString(e.Revision)) + } + for _, link := range e.Evidence { + fmt.Fprintf(&body, "- Evidence <%s>\n", html.EscapeString(link)) + } + return body.String(), nil +} + +// Only marker lines at the start of a provider-authored body are records. +func appendEvents(body string, yield func(Event)) { + for line := range strings.SplitSeq(body, "\n") { + line = strings.TrimSuffix(line, "\r") + if !strings.HasPrefix(line, OccurrencePrefix) || !strings.HasSuffix(line, occurrenceSuffix) { + return + } + input := strings.TrimSuffix(strings.TrimPrefix(line, OccurrencePrefix), occurrenceSuffix) + if event, err := ParseEvent(input); err == nil { + yield(event) + } + } +} + +func decodeJSON(input string, dest any) error { + decoder := json.NewDecoder(strings.NewReader(input)) + decoder.DisallowUnknownFields() + if err := decoder.Decode(dest); err != nil { + return err + } + if err := decoder.Decode(new(json.RawMessage)); err != io.EOF { + return fmt.Errorf("expected one JSON object") + } + return nil +} diff --git a/internal/feedback/event_test.go b/internal/feedback/event_test.go new file mode 100644 index 00000000..f7f4acc3 --- /dev/null +++ b/internal/feedback/event_test.go @@ -0,0 +1,77 @@ +package feedback + +import ( + "os" + "strings" + "testing" +) + +func TestCountDistinctConfirmedOccurrencesAcrossBodies(t *testing.T) { + read := func(name string) Event { + t.Helper() + data, err := os.ReadFile("../../testdata/workflow-feedback/" + name + ".json") + if err != nil { + t.Fatal(err) + } + event, err := ParseEvent(string(data)) + if err != nil { + t.Fatal(err) + } + return event + } + original := read("release-0.6.2") + retry := read("release-0.6.3") + third := read("synthetic-third-release") + body := func(event Event) string { + t.Helper() + value, err := event.commentBody() + if err != nil { + t.Fatal(err) + } + return value + } + firstLine := func(event Event) string { + line, _, _ := strings.Cut(body(event), "\n") + return line + } + + state := snapshot{events: make(map[string]occurrence)} + state.addBody(firstLine(original)+"\n"+firstLine(retry)+"\n\nOriginal issue body", true, 0) + state.addBody(body(retry), true, 24) + state.addBody(body(retry), true, 25) + state.addBody("A quoted example\n\n"+body(third), true, 26) + state.addBody(body(third), false, 27) + if state.confirmed != 2 || state.events[third.Key()].confirmed { + t.Fatalf("wrong confirmed count after duplicates and untrusted report: %+v", state) + } + state.addBody(body(third), true, 28) + if state.confirmed != 3 || state.events[third.Key()].commentID != 28 { + t.Fatalf("trusted confirmation failed to reconcile the original key: %+v", state) + } + otherInstance := third + otherInstance.SourceInstance = "another-instance" + state.addBody(body(otherInstance), true, 29) + if state.confirmed != 4 { + t.Fatalf("separate source instances shared an event key: %+v", state) + } +} + +func TestFeedbackCommentKeepsTypedMarkupInert(t *testing.T) { + data, err := os.ReadFile("../../testdata/workflow-feedback/release-0.6.2.json") + if err != nil { + t.Fatal(err) + } + event, err := ParseEvent(string(data)) + if err != nil { + t.Fatal(err) + } + event.Summary = "" + event.Revision = "" + body, err := event.commentBody() + if err != nil { + t.Fatal(err) + } + if strings.Contains(body, "