sdtk-spec-kit 0.10.0 → 0.12.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (65) hide show
  1. package/README.md +1 -1
  2. package/assets/manifest/toolkit-bundle.manifest.json +207 -47
  3. package/assets/manifest/toolkit-bundle.sha256.txt +54 -22
  4. package/assets/toolkit/toolkit/AGENTS.md +2 -1
  5. package/assets/toolkit/toolkit/SDTK_TOOLKIT.md +5 -1
  6. package/assets/toolkit/toolkit/runtimes/claude/CLAUDE_TEMPLATE.md +4 -0
  7. package/assets/toolkit/toolkit/scripts/install-claude-skills.ps1 +18 -0
  8. package/assets/toolkit/toolkit/scripts/install-codex-skills.ps1 +1 -0
  9. package/assets/toolkit/toolkit/skills/sdtk-arch/SKILL.md +2 -2
  10. package/assets/toolkit/toolkit/skills/sdtk-ba/SKILL.md +2 -2
  11. package/assets/toolkit/toolkit/skills/sdtk-customer-qa-sheet/SKILL.md +117 -0
  12. package/assets/toolkit/toolkit/skills/sdtk-customer-qa-sheet/references/PROFILE_TEMPLATE.md +60 -0
  13. package/assets/toolkit/toolkit/skills/sdtk-customer-qa-sheet/scripts/oq_sync.py +349 -0
  14. package/assets/toolkit/toolkit/skills/sdtk-customer-qa-sheet/scripts/test_oq_sync.py +175 -0
  15. package/assets/toolkit/toolkit/skills/sdtk-db-design/SKILL.md +130 -0
  16. package/assets/toolkit/toolkit/skills/sdtk-db-design/references/REVIEW_PROCESS.md +82 -0
  17. package/assets/toolkit/toolkit/skills/sdtk-pm/SKILL.md +1 -1
  18. package/assets/toolkit/toolkit/skills/sdtk-screen-design-xlsx/SKILL.md +104 -0
  19. package/assets/toolkit/toolkit/skills/sdtk-screen-design-xlsx/references/REVIEW_AND_MISTAKES.md +63 -0
  20. package/assets/toolkit/toolkit/skills/sdtk-screen-design-xlsx/references/SCR01.json +46 -0
  21. package/assets/toolkit/toolkit/skills/sdtk-screen-design-xlsx/references/SCR01.png +0 -0
  22. package/assets/toolkit/toolkit/skills/sdtk-screen-design-xlsx/references/SPEC_SCHEMA.md +208 -0
  23. package/assets/toolkit/toolkit/skills/sdtk-screen-design-xlsx/references/example_spec.yaml +115 -0
  24. package/assets/toolkit/toolkit/skills/sdtk-screen-design-xlsx/scripts/build_design_xlsx.py +550 -0
  25. package/assets/toolkit/toolkit/skills/sdtk-screen-design-xlsx/scripts/design_spec.py +305 -0
  26. package/assets/toolkit/toolkit/skills/sdtk-screen-design-xlsx/scripts/export_preview.py +111 -0
  27. package/assets/toolkit/toolkit/skills/sdtk-screen-design-xlsx/scripts/export_spec_md.py +181 -0
  28. package/assets/toolkit/toolkit/skills/sdtk-screen-design-xlsx/scripts/make_template.py +113 -0
  29. package/assets/toolkit/toolkit/skills/sdtk-screen-design-xlsx/scripts/test_screen_design.py +198 -0
  30. package/assets/toolkit/toolkit/skills/sdtk-screen-design-xlsx/scripts/uia_dump.py +64 -0
  31. package/assets/toolkit/toolkit/skills/sdtk-screen-design-xlsx/scripts/validate_spec.py +260 -0
  32. package/assets/toolkit/toolkit/skills/sdtk-session-handoff/SKILL.md +76 -0
  33. package/assets/toolkit/toolkit/skills/sdtk-session-handoff/references/HANDOFF_TEMPLATE.md +63 -0
  34. package/assets/toolkit/toolkit/skills/sdtk-session-handoff/references/MOVING_A_PROJECT.md +18 -0
  35. package/assets/toolkit/toolkit/skills/sdtk-session-handoff/scripts/dirty_files.py +133 -0
  36. package/assets/toolkit/toolkit/skills/sdtk-session-handoff/scripts/test_dirty_files.py +94 -0
  37. package/assets/toolkit/toolkit/skills/sdtk-xlsx-safe-edit/SKILL.md +4 -1
  38. package/assets/toolkit/toolkit/skills/sdtk-xlsx-safe-edit/scripts/test_metadata.py +76 -0
  39. package/assets/toolkit/toolkit/skills/sdtk-xlsx-safe-edit/scripts/xlsx_xml_edit.py +65 -1
  40. package/assets/toolkit/toolkit/skills/skills.catalog.yaml +96 -0
  41. package/assets/toolkit/toolkit/skills-claude/arch/SKILL.md +15 -2
  42. package/assets/toolkit/toolkit/skills-claude/ba/SKILL.md +8 -4
  43. package/assets/toolkit/toolkit/skills-claude/customer-qa-sheet/SKILL.md +115 -0
  44. package/assets/toolkit/toolkit/skills-claude/db-design/SKILL.md +128 -0
  45. package/assets/toolkit/toolkit/skills-claude/dev/SKILL.md +33 -2
  46. package/assets/toolkit/toolkit/skills-claude/dev-backend/SKILL.md +10 -0
  47. package/assets/toolkit/toolkit/skills-claude/dev-frontend/SKILL.md +10 -0
  48. package/assets/toolkit/toolkit/skills-claude/pm/SKILL.md +14 -3
  49. package/assets/toolkit/toolkit/skills-claude/qa/SKILL.md +40 -2
  50. package/assets/toolkit/toolkit/skills-claude/screen-design-xlsx/SKILL.md +101 -0
  51. package/assets/toolkit/toolkit/skills-claude/session-handoff/SKILL.md +74 -0
  52. package/assets/toolkit/toolkit/skills-claude/test-case-spec/SKILL.md +6 -0
  53. package/assets/toolkit/toolkit/skills-claude/xlsx-safe-edit/SKILL.md +4 -1
  54. package/assets/toolkit/toolkit/templates/README.md +3 -0
  55. package/assets/toolkit/toolkit/templates/docs/database/DATABASE_SPEC_TEMPLATE.md +14 -0
  56. package/assets/toolkit/toolkit/templates/screen-design-xlsx/ja-default/TEMPLATE.md +247 -0
  57. package/assets/toolkit/toolkit/templates/screen-design-xlsx/ja-default/template.xlsx +0 -0
  58. package/package.json +1 -1
  59. package/src/commands/help.js +7 -2
  60. package/src/lib/args.js +5 -2
  61. package/src/lib/design-handoff-provenance.js +30 -5
  62. package/src/lib/office-ingest.js +376 -0
  63. package/src/lib/requirement-analysis.js +77 -41
  64. package/src/lib/requirement-sources.js +259 -0
  65. package/src/lib/scope.js +4 -4
@@ -131,6 +131,7 @@ Get-ChildItem -LiteralPath $skillsSrc -Directory | ForEach-Object {
131
131
  $templateTree = switch ($_.Name) {
132
132
  'sdtk-smoke-test-spec' { 'templates/smoke-test' }
133
133
  'sdtk-test-case-xlsx' { 'templates/test-case-xlsx' }
134
+ 'sdtk-screen-design-xlsx' { 'templates/screen-design-xlsx' }
134
135
  default { $null }
135
136
  }
136
137
  if ($templateTree) {
@@ -34,7 +34,7 @@ digraph sdtk_arch_flow {
34
34
  ```
35
35
 
36
36
  ## Process
37
- 1. Read BA spec and PRD/backlog.
37
+ 1. Read BA spec and PRD/backlog. For source evidence use the readable paths and line ranges in `.sdtk/spec/requirements/SOURCE_INDEX_[FEATURE_KEY].md` when it exists (cite `source_path` when it lists more than one source).
38
38
  2. Read `sdtk-spec.config.json` for project stack assumptions (backend/frontend/db/auth).
39
39
  3. If architecture output includes API contracts/flows, read and apply:
40
40
  - `toolkit/templates/docs/api/YAML_CREATION_RULES.md`
@@ -57,7 +57,7 @@ digraph sdtk_arch_flow {
57
57
  - OpenAPI YAML + API endpoint markdown
58
58
  - API flow list
59
59
  - API design detail spec (when `orchestration.apiDesignDetailMode` is `auto/on`)
60
- - Database spec (if DB impact exists)
60
+ - Database spec (if DB impact exists; a new table, a legacy replacement or a migration that can meet real data -> run `sdtk-db-design` first)
61
61
  - Design layout (if UI impact exists) - must be created before flow-action spec
62
62
  - Flow-action spec (if UI impact exists) - must reference design layout as fallback source
63
63
  10. Ensure mapping UC/BR -> DB/API/screens and run output hygiene checks:
@@ -30,7 +30,7 @@ questions from the Open Questions For Human Review section must be carried
30
30
  forward as explicit OQ-xx items in BA_SPEC rather than silently resolved.
31
31
 
32
32
  ## Process
33
- 1. Read `docs/product/PROJECT_INITIATION_[FEATURE_KEY].md` and any source requirements.
33
+ 1. Read `docs/product/PROJECT_INITIATION_[FEATURE_KEY].md` and any source requirements. When `.sdtk/spec/requirements/SOURCE_INDEX_[FEATURE_KEY].md` exists (from `sdtk-spec analyze`), read it first and open only the readable sources and line ranges it lists: Office files are already extracted to Markdown there, so never parse the binary copies.
34
34
  2. Produce:
35
35
  - Glossary
36
36
  - BR-xx (numbered)
@@ -41,6 +41,6 @@ forward as explicit OQ-xx items in BA_SPEC rather than silently resolved.
41
41
  - Traceability summary table (REQ -> UC/BR/AC)
42
42
  3. If source requirements are VI/JP, preserve the original text and add a literal EN translation in appendices.
43
43
  4. For benchmark runs, apply `governance/ai/core/SDTK_BENCHMARK_OQ_POLICY.md`: keep benchmark-expected open questions explicitly OPEN and do not silently resolve them in BA output.
44
- 5. If anything is unclear, record OQ-xx in BA_SPEC "Open Questions" and escalate to `@pm` for a decision.
44
+ 5. If anything is unclear, record OQ-xx in BA_SPEC "Open Questions" and escalate to `@pm` for a decision. OQs the customer must answer through their Q&A Excel sheet go there with `sdtk-customer-qa-sheet` (answers come back keyed by OQ id).
45
45
  6. Update `SHARED_PLANNING.md` and `QUALITY_CHECKLIST.md` Phase 2.
46
46
  7. Handoff: `@pm specs ready for PRD`.
@@ -0,0 +1,117 @@
1
+ ---
2
+ name: sdtk-customer-qa-sheet
3
+ description: Use when open questions (OQ-xx, 確認事項, 仕様確認) must go to a customer through their hand-maintained Q&A or issue-tracking Excel sheet (one numbered question per row, an answer column), when reading the customer's answers back into the spec / decision log, or when writing replies to questions the customer asked in that sheet.
4
+ ---
5
+
6
+ # SDTK-SPEC Customer Q&A Sheet: questions, answers, replies
7
+
8
+ The sheet is a customer-facing record. Every row you add is read by the customer and answered in
9
+ writing, so a row must be correct, not a duplicate, in the sheet's own style, and approved by the
10
+ person before it lands. The workbook itself is hand-maintained.
11
+
12
+ **REQUIRED SUB-SKILL:** `sdtk-xlsx-safe-edit` — preflight, backup, XML route for every write. Never save
13
+ this workbook through Excel or openpyxl: that rewrites fonts and row heights on every other sheet.
14
+
15
+ <!-- neutral-only -->
16
+ > **Installed as a runtime skill** (for example under `.codex/skills/`): read `toolkit/skills/sdtk-<name>/` in the
17
+ > paths below as the installed skill folder of that name (this one or a sibling).
18
+ <!-- /neutral-only -->
19
+
20
+ ## Critical Constraints
21
+
22
+ 1. **Nothing is written before the person approves the exact row values** (or the exact reply text).
23
+ "The PM approved the wording" is not approval of row values, placement or numbering.
24
+ 2. **Never overwrite a cell that holds text.** New questions go into empty rows; replies are appended
25
+ after existing answer text. The customer's answer text is never edited.
26
+ 3. **Search before asking.** Every candidate is checked against the existing rows; overlap with an
27
+ unanswered row → reference it or drop the question; answered already → do not ask again.
28
+ 4. **Rows and OQs are matched by id** — the `OQ-xx` in an OQ column or in the question text, and the
29
+ sheet's No — never by row position.
30
+ 5. **Facts stated to the customer come from the code that runs, logs or a measurement**, not from
31
+ comments or design documents.
32
+
33
+ ## Project profile (read first)
34
+
35
+ Project facts live in the project repository, not here: find `qa_sheet_profile.md` by file search over the
36
+ working tree (it may be untracked; `git ls-files` misses it). It names the workbook, sheet, header row,
37
+ column map, our contact name, the customer's, category values, numbering format, answer-block format,
38
+ ordering rule, and a ```json block the script reads. No profile → build one from
39
+ `toolkit/skills/sdtk-customer-qa-sheet/references/PROFILE_TEMPLATE.md` by reading the sheet, and confirm it with
40
+ the person.
41
+
42
+ Script: `toolkit/skills/sdtk-customer-qa-sheet/scripts/oq_sync.py` (`oqs`, `sheet`, `export`, `answers`, `write`).
43
+ It reads the workbook from a copy with openpyxl and writes only through `sdtk-xlsx-safe-edit`'s `xlsx_xml_edit`
44
+ (the sheet part changes, every other part stays byte-identical, a `.bak` is kept).
45
+
46
+ ## Process
47
+
48
+ Read the profile, then follow the section that matches the request: A (adding questions), B (reading answers)
49
+ or C (replying to the customer). Each ends with a draft for the person before anything is written.
50
+
51
+ ### A. Adding questions
52
+
53
+ 1. **Read the sheet read-only** (`oq_sync.py sheet --profile …`): the last 5–10 filled rows for style, the
54
+ first empty number, pre-numbered empty rows, where data validation / conditional formatting end.
55
+ 2. **Collect the candidates.** From the spec: `oq_sync.py export --profile … --spec docs/specs/BA_SPEC_<KEY>.md
56
+ --out <draft>.md` lists every OPEN OQ not yet in the sheet with a proposed No and row, and the rows that share
57
+ words with it ("possibly related" — rows written before OQ ids were used carry no id); OQs already in the
58
+ sheet are shown with their No (answered or not). Other candidates come from the person or the work.
59
+ 3. **Check every candidate against existing rows.** Search the question, detail and function columns for
60
+ the same topic. Overlap with an unanswered row → reference it (e.g. "関連 No024") or drop the question.
61
+ 4. **Keep only questions that block work:** the spec leaves a user-visible or data-affecting behaviour
62
+ undefined, or the spec cannot be built as written and a deviation needs consent. Do not ask what the spec
63
+ states clearly. A mockup is an illustration, not a decision; when a cell and a mockup disagree, quote
64
+ both. Before asking about a limit or rule in your own system, read the code that enforces it and state
65
+ what it really counts.
66
+ 5. **Write each row's text in this shape** (the customer's language and the sheet's style):
67
+ 1. context, 1–2 sentences: the spec sheet / section it comes from, and the current behaviour stated plainly
68
+ ("not implemented yet", "limited to 20 in total");
69
+ 2. the question; several points → one numbered item each — (1), (2)… — each answerable alone;
70
+ 3. choices when they help: (A), (B)… with our proposal marked as the profile says (e.g. "… 弊社案");
71
+ 4. a closing ask (e.g. "どちらがよろしいでしょうか。").
72
+ Each row carries its `OQ-xx` (OQ column, or the profile's `oq_tag` at the start of the text). Customer text
73
+ carries no code paths, no internal ticket ids, and no apology or correction of an earlier document unless
74
+ the person asks for one.
75
+ 6. **Draft for review:** the export draft completed with, per row, every column value exactly as it will be
76
+ written, the existing rows on the same topic (or "none"), and a translation for the reviewer (not written to
77
+ Excel). End with the open choices and a default for each (start number, one row vs one row per point,
78
+ order, column values, date).
79
+ 7. **Write only after the person approves.** Save the approved rows as JSON (`[{"row", "oq", "values": {<profile
80
+ column key>: text}}]`), run `oq_sync.py write --profile … --rows <file>` (dry run), then with `--apply`.
81
+ The script refuses rows that already hold a question, OQs already in the sheet, unknown columns, and any
82
+ value in the answer column. Report: rows written, No, backup path.
83
+
84
+ ### B. Reading the customer's answers
85
+
86
+ 1. `oq_sync.py answers --profile … --snapshot <last>.json --save-snapshot <new>.json` — rows whose answer is
87
+ non-empty and changed since the last snapshot, each with its `OQ-xx` ids (`unmatched: true` when the row
88
+ names none). Keep the snapshot next to the profile.
89
+ 2. Per row: question, answer verbatim, the decision it implies, the specs or tasks it changes, and whether it
90
+ is ambiguous. Ambiguous → draft a follow-up row ("関連 No…") under section A. Any statement about how your
91
+ system works follows constraint 5.
92
+ 3. **Propose** the spec update, keyed by OQ id: in BA_SPEC §5.2 the row's Status → `RESOLVED`, Resolution →
93
+ the decision + `(<sheet> No<n>, <answer date>)`; a dated row in the decision log. Show the patch; apply it
94
+ after the person agrees. Unmatched rows are reported, never guessed onto an OQ.
95
+
96
+ ### C. Replying to a question the customer asked
97
+
98
+ 1. Establish every fact you will state from the code that executes, logs or a measurement; note which of
99
+ these each fact rests on. Behaviour you did not measure is stated as design, not as observed.
100
+ 2. When the person's statement contradicts the code (for example which version uses which path), write what
101
+ the code does and say so explicitly in the draft.
102
+ 3. Draft the reply in the answer-block format from the profile (e.g. `YYYY/MM/DD <our name>` + newline +
103
+ text), in the sheet's existing style: 1–2 lines per item; several product versions → "path 1 / path 2"
104
+ with one note on top; commands short, one per line. Show the draft unless the person approved this exact
105
+ text.
106
+ 4. Write it **after** any existing text in the answer cell (XML route of `sdtk-xlsx-safe-edit`), never over it.
107
+
108
+ ## Red flags — stop
109
+
110
+ | Thought | Reality |
111
+ |---|---|
112
+ | "The PM approved the wording, just write it" | Approved wording ≠ approved row values / placement / a reply you composed. Show what you will write unless it was approved verbatim. |
113
+ | "Save once through Excel, it's quicker" | Every other sheet's layout changes. XML route. |
114
+ | "This question is new" | You have not searched the existing rows yet. |
115
+ | "The answers are in the same order as our OQs" | Match by OQ id; report rows without one. |
116
+ | "The mockup shows it, so it's required" | Ask only if the spec text is silent or contradicts it. |
117
+ | "I know how the app behaves" / "the design doc says so" | Read the code path that runs; quote what it counts or returns. |
@@ -0,0 +1,60 @@
1
+ # Q&A sheet profile: <project>
2
+
3
+ Profile for the `sdtk-customer-qa-sheet` skill. Keep it in the project repo as `qa_sheet_profile.md` (it may stay
4
+ untracked). Sections 1–5 are for people and agents; the json block at the end is what `oq_sync.py` reads.
5
+
6
+ ## 1. Workbook
7
+ | | |
8
+ |---|---|
9
+ | Workbook | `<repo-relative path>.xlsx` |
10
+ | Sheet | `<sheet name>` (other sheets in the workbook belong to <who> — never touched) |
11
+ | Header row | `<n>`; first data row `<n>` |
12
+ | Spec sheets the questions cite | `<sheet / document names>` |
13
+
14
+ ## 2. Columns
15
+ | Column | Header | Our value when we ask | Value when the customer asks |
16
+ |---|---|---|---|
17
+ | D | No | number, format `00000` | — |
18
+ | … | 区分 / category | … | … |
19
+ | … | 機能 / function | … | … |
20
+ | … | 内容 / question | question text | question text |
21
+ | … | 回答 / answer | (empty — customer writes) | our answer block |
22
+ | … | 連絡者 / asked by | `<our contact name>` | `<customer contact name>` |
23
+ | … | 対応 / must answer | `<customer party>` | `<our party>` |
24
+ | … | OQ id (optional) | `OQ-xx` | — |
25
+ | (others) | | empty | empty |
26
+
27
+ ## 3. Conventions
28
+ - Numbering: next number after the last filled row; pre-numbered empty rows are filled first.
29
+ - One question topic per row; points inside a row numbered (1), (2)…
30
+ - Proposal marker: `… 弊社案` after a choice, or `(弊社案:…)` after a numbered point.
31
+ - Related row reference at the start of the text: `関連 No0xx`.
32
+ - Answer block: `YYYY/MM/DD <name>` on the first line, then the text; later blocks are appended below.
33
+ - Row order for a batch: <e.g. order of the sections in the spec sheet>.
34
+ - Function column naming: <e.g. "<spec sheet> <section number>. <section title>">.
35
+
36
+ ## 4. Layout facts
37
+ - Data validation / conditional formatting end at row `<n>` — extend when adding rows past it.
38
+ - Template row for new rows: `<n>` (same styles as the last filled rows).
39
+ - Row height: <how existing rows are sized>.
40
+
41
+ ## 5. Review draft
42
+ - Location: `<path>`; translation language for the reviewer: `<lang>`.
43
+
44
+ ## 6. Script block (`oq_sync.py`)
45
+ Column keys are yours; `no`, `question` and `answer` are required, `oq` is optional (without it the id goes into
46
+ the question text as `oq_tag`). `workbook` is relative to this file.
47
+
48
+ ```json
49
+ {
50
+ "workbook": "<relative path>.xlsx",
51
+ "sheet": "<sheet name>",
52
+ "header_row": 5,
53
+ "first_data_row": 6,
54
+ "template_row": null,
55
+ "no_format": "00000",
56
+ "oq_tag": "[{id}]",
57
+ "columns": {"no": "D", "category": "E", "function": "F", "question": "G", "answer": "H",
58
+ "asked_by": "I", "must_answer": "J"}
59
+ }
60
+ ```
@@ -0,0 +1,349 @@
1
+ #!/usr/bin/env python3
2
+ """Bridge between the open questions (OQ-xx) of SDTK specs and a customer's hand-maintained Q&A workbook.
3
+
4
+ oq_sync.py oqs --spec BA_SPEC.md list OQ rows of the spec(s) (id, status, question)
5
+ oq_sync.py sheet --profile qa_sheet_profile.md dump the sheet's rows (read-only)
6
+ oq_sync.py export --profile P --spec BA_SPEC.md [--out f] draft of rows for OPEN OQs not yet in the sheet
7
+ oq_sync.py answers --profile P [--snapshot s.json] [--save-snapshot s.json]
8
+ answered rows changed since the snapshot, keyed by OQ id
9
+ oq_sync.py write --profile P --rows approved.json [--apply]
10
+ write approved rows (XML route; dry-run without --apply)
11
+
12
+ The profile is the project's qa_sheet_profile.md; the script reads its first ```json block (keys below). Rows are
13
+ matched to OQs by id (an OQ column, or "[OQ-07]" in the question text) — never by position. The workbook is only
14
+ read with openpyxl; `write` goes through sdtk-xlsx-safe-edit's xlsx_xml_edit (other parts stay byte-identical).
15
+
16
+ Profile JSON keys: workbook, sheet, header_row, first_data_row, template_row (optional, default = last filled
17
+ row), columns {no, question, answer, oq (optional), plus any others used in approved rows}, no_format (e.g.
18
+ "00000" or "int"), oq_tag (default "[{id}]").
19
+ """
20
+ from __future__ import annotations
21
+
22
+ import argparse
23
+ import hashlib
24
+ import json
25
+ import os
26
+ import re
27
+ import shutil
28
+ import sys
29
+ import tempfile
30
+
31
+ HERE = os.path.dirname(os.path.abspath(__file__))
32
+ for _name in ("sdtk-xlsx-safe-edit", "xlsx-safe-edit"): # toolkit layout / Claude skills layout
33
+ _candidate = os.path.join(HERE, "..", "..", _name, "scripts")
34
+ if os.path.isdir(_candidate):
35
+ sys.path.insert(0, os.path.normpath(_candidate))
36
+ break
37
+
38
+ OQ_ID = re.compile(r"\bOQ-\d+\b")
39
+
40
+
41
+ class SyncError(RuntimeError):
42
+ pass
43
+
44
+
45
+ # ---------------------------------------------------------------------------------------------------- spec side
46
+ def _cells(line):
47
+ return [c.strip() for c in line.strip().strip("|").split("|")]
48
+
49
+
50
+ def read_oqs(spec_paths):
51
+ """OQ rows from every markdown table whose header has a Q-ID / ID column and a Question column."""
52
+ out = []
53
+ for path in spec_paths:
54
+ with open(path, encoding="utf-8") as f:
55
+ lines = f.read().splitlines()
56
+ header = None
57
+ for i, line in enumerate(lines):
58
+ if not line.lstrip().startswith("|"):
59
+ header = None
60
+ continue
61
+ cells = _cells(line)
62
+ if header is None:
63
+ low = [c.lower() for c in cells]
64
+ idc = next((j for j, c in enumerate(low) if c in ("q-id", "id", "oq", "oq id", "oq-id")), None)
65
+ qc = next((j for j, c in enumerate(low) if c.startswith("question")), None)
66
+ if idc is not None and qc is not None:
67
+ st = next((j for j, c in enumerate(low) if c.startswith("status")), None)
68
+ header = (idc, qc, st)
69
+ continue
70
+ if set("".join(cells)) <= set("-: "):
71
+ continue
72
+ idc, qc, st = header
73
+ if idc >= len(cells) or not OQ_ID.fullmatch(cells[idc]):
74
+ continue
75
+ out.append({"id": cells[idc], "question": cells[qc] if qc < len(cells) else "",
76
+ "status": (cells[st] if st is not None and st < len(cells) else "").upper(),
77
+ "source": f"{path}:{i + 1}"})
78
+ seen = {}
79
+ for oq in out:
80
+ if oq["id"] in seen:
81
+ raise SyncError(f"{oq['id']} appears twice: {seen[oq['id']]} and {oq['source']}")
82
+ seen[oq["id"]] = oq["source"]
83
+ return out
84
+
85
+
86
+ # ---------------------------------------------------------------------------------------------------- sheet side
87
+ def load_profile(path):
88
+ with open(path, encoding="utf-8") as f:
89
+ text = f.read()
90
+ m = re.search(r"```json\s*\n(.*?)\n```", text, re.S)
91
+ if not m:
92
+ raise SyncError(f"{path}: no ```json block (see the profile template)")
93
+ prof = json.loads(m.group(1))
94
+ for key in ("workbook", "sheet", "header_row", "first_data_row", "columns"):
95
+ if key not in prof:
96
+ raise SyncError(f"profile: missing key {key!r}")
97
+ for key in ("no", "question", "answer"):
98
+ if key not in prof["columns"]:
99
+ raise SyncError(f"profile: columns.{key} missing")
100
+ base = os.path.dirname(os.path.abspath(path))
101
+ if not os.path.isabs(prof["workbook"]):
102
+ candidates = [os.path.join(base, prof["workbook"]), os.path.abspath(prof["workbook"])]
103
+ prof["workbook"] = next((c for c in candidates if os.path.exists(c)), candidates[0])
104
+ prof.setdefault("oq_tag", "[{id}]")
105
+ prof.setdefault("no_format", "int")
106
+ return prof
107
+
108
+
109
+ def _text(v):
110
+ if v is None:
111
+ return ""
112
+ if isinstance(v, float) and v.is_integer():
113
+ v = int(v)
114
+ return str(v).strip()
115
+
116
+
117
+ def read_sheet(prof):
118
+ """Rows from first_data_row to the last row with any mapped column filled. Read-only."""
119
+ from openpyxl import load_workbook
120
+ tmp = tempfile.mkdtemp(prefix="oqsync-")
121
+ try:
122
+ copy = os.path.join(tmp, "read.xlsx")
123
+ shutil.copy2(prof["workbook"], copy) # never hold the person's file open
124
+ wb = load_workbook(copy, data_only=True) # not read_only: that mode trusts <dimension>
125
+ ws = wb[prof["sheet"]]
126
+ cols = prof["columns"]
127
+ rows = []
128
+ for r, row in enumerate(ws.iter_rows(min_row=prof["first_data_row"], values_only=True), prof["first_data_row"]):
129
+ get = lambda col: _text(row[_col_index(col)] if _col_index(col) < len(row) else None) # noqa: E731
130
+ rec = {k: get(c) for k, c in cols.items()}
131
+ rec["row"] = r
132
+ ids = set(OQ_ID.findall(rec.get("oq", "")))
133
+ ids |= set(OQ_ID.findall(rec.get("question", "")))
134
+ rec["oq_ids"] = sorted(ids)
135
+ rows.append(rec)
136
+ while rows and not any(rows[-1][k] for k in cols if k != "no"):
137
+ rows.pop()
138
+ return rows
139
+ finally:
140
+ shutil.rmtree(tmp, ignore_errors=True)
141
+
142
+
143
+ def _col_index(col):
144
+ n = 0
145
+ for ch in col:
146
+ n = n * 26 + ord(ch) - 64
147
+ return n - 1
148
+
149
+
150
+ def format_no(prof, n):
151
+ fmt = prof["no_format"]
152
+ return str(n).zfill(len(fmt)) if fmt.strip("0") == "" and fmt else n
153
+
154
+
155
+ def next_number(rows):
156
+ """First pre-numbered empty row, else last number + 1."""
157
+ for rec in rows:
158
+ if rec["no"] and not rec["question"]:
159
+ return int(re.sub(r"\D", "", rec["no"]) or 0), rec["row"]
160
+ nums = [int(re.sub(r"\D", "", r["no"])) for r in rows if re.sub(r"\D", "", r["no"])]
161
+ last_row = rows[-1]["row"] if rows else None
162
+ return (max(nums) + 1 if nums else 1), (last_row + 1 if last_row else None)
163
+
164
+
165
+ # ---------------------------------------------------------------------------------------------------- commands
166
+ def cmd_export(prof, spec_paths, out):
167
+ oqs = read_oqs(spec_paths)
168
+ rows = read_sheet(prof)
169
+ in_sheet = {i: r for r in rows for i in r["oq_ids"]}
170
+ number, row = next_number(rows)
171
+ lines = [f"# Q&A sheet draft — {os.path.basename(prof['workbook'])} / {prof['sheet']}", "",
172
+ "Draft only. Rewrite each question in the sheet's style and language (SKILL.md A.4), check related rows,",
173
+ "then get the person's approval before `write`.", "",
174
+ "\"Possibly related\" lists rows sharing words with the OQ — a hint for step A.3, not a verdict: rows",
175
+ "written before OQ ids were used carry no id, so search the sheet yourself too.", "",
176
+ "| OQ | Status in spec | In sheet | Possibly related (No, answered?) | Proposed No | Sheet row | Question (spec wording) |",
177
+ "|---|---|---|---|---|---|---|"]
178
+ proposed = []
179
+ for oq in oqs:
180
+ if oq["id"] in in_sheet:
181
+ r = in_sheet[oq["id"]]
182
+ state = f"No {r['no']} (row {r['row']}){' — answered' if r['answer'] else ''}"
183
+ lines.append(f"| {oq['id']} | {oq['status'] or '?'} | {state} | — | — | — | {oq['question']} |")
184
+ continue
185
+ if oq["status"] and oq["status"] != "OPEN":
186
+ lines.append(f"| {oq['id']} | {oq['status']} | no | — | — (not open) | — | {oq['question']} |")
187
+ continue
188
+ hints = related_rows(oq["question"], rows)
189
+ hint = ", ".join(f"No {r['no']} ({'answered' if r['answer'] else 'open'})" for r in hints[:3]) or "none"
190
+ no = format_no(prof, number)
191
+ lines.append(f"| {oq['id']} | {oq['status'] or '?'} | no | {hint} | {no} | {row} | {oq['question']} |")
192
+ proposed.append({"oq": oq["id"], "no": no, "row": row, "question": oq["question"], "source": oq["source"],
193
+ "related": [r["no"] for r in hints]})
194
+ number += 1
195
+ row = row + 1 if row else None
196
+ lines += ["", "Proposed rows (fill `values` per profile column, then save as the approved rows file):", "",
197
+ "```json", json.dumps([{"row": p["row"], "oq": p["oq"],
198
+ "values": {"no": p["no"], "question": prof["oq_tag"].format(id=p["oq"]) + " ",
199
+ **({"oq": p["oq"]} if "oq" in prof["columns"] else {})}}
200
+ for p in proposed], ensure_ascii=False, indent=2), "```"]
201
+ text = "\n".join(lines) + "\n"
202
+ if out:
203
+ with open(out, "w", encoding="utf-8") as f:
204
+ f.write(text)
205
+ return text, proposed
206
+
207
+
208
+ _STOP = {"what", "which", "when", "where", "there", "their", "this", "that", "with", "from", "have", "should",
209
+ "would", "could", "does", "will", "shall", "about", "into", "than", "then", "them", "they", "also", "only"}
210
+
211
+
212
+ def _tokens(text):
213
+ """Words of 4+ letters (minus a few function words) and CJK bigrams — enough to point at likely duplicates."""
214
+ text = text.lower()
215
+ words = {w for w in re.findall(r"[a-z0-9]{4,}", text) if w not in _STOP}
216
+ words |= {w[:-1] for w in words if w.endswith("s")}
217
+ cjk = re.findall(r"[\u3040-\u30ff\u3400-\u9fff]+", text)
218
+ return words | {run[i:i + 2] for run in cjk for i in range(len(run) - 1)}
219
+
220
+
221
+ def related_rows(question, rows, minimum=2):
222
+ """Rows of the sheet sharing at least `minimum` tokens with the question, best first. A hint, not a verdict."""
223
+ mine = _tokens(question)
224
+ scored = []
225
+ for rec in rows:
226
+ if not rec.get("question"):
227
+ continue
228
+ shared = len(mine & _tokens(" ".join(rec.get(k, "") for k in rec if k not in ("row", "oq_ids", "no"))))
229
+ if shared >= minimum:
230
+ scored.append((shared, rec["row"], rec))
231
+ return [rec for _, _, rec in sorted(scored, key=lambda t: (-t[0], t[1]))]
232
+
233
+
234
+ def _digest(rec):
235
+ return hashlib.sha256(rec["answer"].encode("utf-8")).hexdigest()[:16]
236
+
237
+
238
+ def cmd_answers(prof, snapshot, save):
239
+ rows = read_sheet(prof)
240
+ old = {}
241
+ if snapshot and os.path.exists(snapshot):
242
+ with open(snapshot, encoding="utf-8") as f:
243
+ old = json.load(f)
244
+ changed = []
245
+ for rec in rows:
246
+ if not rec["answer"]:
247
+ continue
248
+ key = rec["no"] or f"row{rec['row']}"
249
+ if old.get(key) == _digest(rec):
250
+ continue
251
+ changed.append({"no": rec["no"], "row": rec["row"], "oq_ids": rec["oq_ids"], "question": rec["question"],
252
+ "answer": rec["answer"], "unmatched": not rec["oq_ids"]})
253
+ if save:
254
+ with open(save, "w", encoding="utf-8") as f:
255
+ json.dump({(r["no"] or f"row{r['row']}"): _digest(r) for r in rows if r["answer"]}, f, indent=1, sort_keys=True)
256
+ return changed
257
+
258
+
259
+ def cmd_write(prof, rows_path, apply):
260
+ from xlsx_xml_edit import SheetXml, package_diff
261
+ with open(rows_path, encoding="utf-8") as f:
262
+ approved = json.load(f)
263
+ current = read_sheet(prof)
264
+ by_row = {r["row"]: r for r in current}
265
+ present = {i for r in current for i in r["oq_ids"]}
266
+ cols = prof["columns"]
267
+ plan = []
268
+ for item in approved:
269
+ r, values = item["row"], item["values"]
270
+ if item.get("oq") in present:
271
+ raise SyncError(f"{item['oq']} is already in the sheet — re-run export")
272
+ existing = by_row.get(r)
273
+ if existing and existing["question"]:
274
+ raise SyncError(f"row {r} already holds a question (No {existing['no']}) — never overwrite")
275
+ if item.get("oq") and item["oq"] not in values.get("question", "") + values.get("oq", ""):
276
+ raise SyncError(f"row {r}: OQ id {item['oq']} must be in the question text or the oq column")
277
+ unknown = set(values) - set(cols)
278
+ if unknown:
279
+ raise SyncError(f"row {r}: columns not in the profile: {sorted(unknown)}")
280
+ if values.get("answer"):
281
+ raise SyncError(f"row {r}: the answer column is the customer's — leave it empty")
282
+ plan.append((r, {cols[k]: v for k, v in values.items()}))
283
+ if not apply:
284
+ return {"dry_run": True, "rows": [{"row": r, "cells": v} for r, v in plan]}
285
+ src = prof["workbook"]
286
+ lock = os.path.join(os.path.dirname(src), "~$" + os.path.basename(src))
287
+ if os.path.exists(lock):
288
+ raise SyncError(f"lock file {lock} exists — the workbook may be open; ask the person to close it")
289
+ backup = src + ".bak"
290
+ shutil.copy2(src, backup)
291
+ last_filled = max((x["row"] for x in current if x["question"]), default=prof["first_data_row"])
292
+ template_row = prof.get("template_row") or last_filled
293
+ sheet = SheetXml(src, prof["sheet"])
294
+ old_last = max([int(n) for n in re.findall(r'<row r="(\d+)"', sheet.xml)] + [last_filled])
295
+ for r, cells in plan:
296
+ sheet.set_row(r, cells, template_row)
297
+ new_last = max(r for r, _ in plan)
298
+ if new_last > old_last:
299
+ sheet.extend_ranges(old_last, new_last) # DV / CF / dimension that end at the last row grow with it
300
+ fd, out = tempfile.mkstemp(suffix=".xlsx", dir=os.path.dirname(src))
301
+ os.close(fd)
302
+ sheet.save(out)
303
+ sheet.zf.close()
304
+ changed = package_diff(src, out)
305
+ if changed != [sheet.part]:
306
+ os.remove(out)
307
+ raise SyncError(f"unexpected parts changed: {changed} — nothing written")
308
+ os.replace(out, src)
309
+ after = {x["row"]: x for x in read_sheet(prof)}
310
+ for r, _ in plan:
311
+ if not after.get(r, {}).get("question"):
312
+ raise SyncError(f"row {r} reads back empty — restore {backup}")
313
+ return {"dry_run": False, "backup": backup, "rows": [r for r, _ in plan], "changed_parts": changed}
314
+
315
+
316
+ def main(argv=None):
317
+ ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
318
+ sub = ap.add_subparsers(dest="cmd", required=True)
319
+ p = sub.add_parser("oqs"); p.add_argument("--spec", nargs="+", required=True)
320
+ p = sub.add_parser("sheet"); p.add_argument("--profile", required=True)
321
+ p = sub.add_parser("export"); p.add_argument("--profile", required=True)
322
+ p.add_argument("--spec", nargs="+", required=True); p.add_argument("--out")
323
+ p = sub.add_parser("answers"); p.add_argument("--profile", required=True)
324
+ p.add_argument("--snapshot"); p.add_argument("--save-snapshot")
325
+ p = sub.add_parser("write"); p.add_argument("--profile", required=True)
326
+ p.add_argument("--rows", required=True); p.add_argument("--apply", action="store_true")
327
+ a = ap.parse_args(argv)
328
+ try:
329
+ if a.cmd == "oqs":
330
+ res = read_oqs(a.spec)
331
+ elif a.cmd == "sheet":
332
+ res = read_sheet(load_profile(a.profile))
333
+ elif a.cmd == "export":
334
+ text, _ = cmd_export(load_profile(a.profile), a.spec, a.out)
335
+ print(text)
336
+ return 0
337
+ elif a.cmd == "answers":
338
+ res = cmd_answers(load_profile(a.profile), a.snapshot, a.save_snapshot)
339
+ else:
340
+ res = cmd_write(load_profile(a.profile), a.rows, a.apply)
341
+ except (SyncError, KeyError, FileNotFoundError) as e:
342
+ print(f"ERROR: {e}", file=sys.stderr)
343
+ return 2
344
+ print(json.dumps(res, ensure_ascii=False, indent=1))
345
+ return 0
346
+
347
+
348
+ if __name__ == "__main__":
349
+ sys.exit(main())