@1aboveio/skills 1.0.10 → 1.0.11

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 (213) hide show
  1. package/.codex-plugin/plugin.json +1 -1
  2. package/.codex-plugin/resources.json +297 -216
  3. package/README.md +3 -3
  4. package/package.json +10 -8
  5. package/skills/app-dev/airflow/SKILL.md +1 -1
  6. package/skills/app-dev/android-foundation/SKILL.md +35 -37
  7. package/skills/app-dev/android-foundation/references/delivery-focus.md +4 -2
  8. package/skills/app-dev/android-foundation/references/feature-work.md +50 -0
  9. package/skills/app-dev/android-foundation/references/setup.md +24 -9
  10. package/skills/app-dev/android-foundation/references/workspace.md +81 -0
  11. package/skills/app-dev/android-foundation/scripts/workspace-runtime/bin/workspaces.mjs +52 -0
  12. package/skills/app-dev/android-foundation/scripts/workspace-runtime/native-workspace.mjs +239 -0
  13. package/skills/app-dev/android-foundation/scripts/workspace-runtime/workspace-lifecycle.mjs +2154 -0
  14. package/skills/app-dev/app-debug/SKILL.md +1 -1
  15. package/skills/app-dev/better-auth/SKILL.md +1 -1
  16. package/skills/app-dev/data-catalog/SKILL.md +1 -1
  17. package/skills/app-dev/data-quality/SKILL.md +1 -1
  18. package/skills/app-dev/ios-foundation/SKILL.md +15 -10
  19. package/skills/app-dev/ios-foundation/references/setup.md +25 -9
  20. package/skills/app-dev/ios-foundation/references/workspace.md +82 -0
  21. package/skills/app-dev/ios-foundation/scripts/workspace-runtime/bin/workspaces.mjs +52 -0
  22. package/skills/app-dev/ios-foundation/scripts/workspace-runtime/native-workspace.mjs +239 -0
  23. package/skills/app-dev/ios-foundation/scripts/workspace-runtime/workspace-lifecycle.mjs +2154 -0
  24. package/skills/app-dev/monorepo/SKILL.md +1 -1
  25. package/skills/app-dev/nextjs-fullstack/SKILL.md +1 -1
  26. package/skills/app-dev/prisma-setup/SKILL.md +1 -1
  27. package/skills/app-dev/pyspark/SKILL.md +1 -1
  28. package/skills/app-dev/python-backend/SKILL.md +1 -1
  29. package/skills/app-dev/shadcn/SKILL.md +1 -1
  30. package/skills/app-dev/zod-v4/SKILL.md +1 -1
  31. package/skills/cicd/cloud-build/SKILL.md +1 -1
  32. package/skills/cicd/cloud-debug/SKILL.md +1 -1
  33. package/skills/cicd/cloud-deploy/SKILL.md +1 -1
  34. package/skills/cicd/docker/SKILL.md +1 -1
  35. package/skills/cicd/github-actions/SKILL.md +1 -1
  36. package/skills/cicd/github-flow/SKILL.md +1 -1
  37. package/skills/cicd/google-cloud/SKILL.md +1 -1
  38. package/skills/cicd/mergify/SKILL.md +1 -1
  39. package/skills/cicd/podman/SKILL.md +1 -1
  40. package/skills/content/article-review/SKILL.md +1 -1
  41. package/skills/content/article-to-image/SKILL.md +1 -1
  42. package/skills/content/flowchart-svg/SKILL.md +1 -1
  43. package/skills/content/image-gen/SKILL.md +1 -1
  44. package/skills/content/mermaid/SKILL.md +1 -1
  45. package/skills/content/wechat-article-writer/SKILL.md +1 -1
  46. package/skills/content/wechat-publisher/SKILL.md +1 -1
  47. package/skills/content/wechat-search/SKILL.md +1 -1
  48. package/skills/content/xai-search/SKILL.md +1 -1
  49. package/skills/core/distill-writing/SKILL.md +3 -3
  50. package/skills/core/distill-writing/references/extraction.md +1 -1
  51. package/skills/core/doc-to-md/SKILL.md +1 -1
  52. package/skills/core/editorial-review/SKILL.md +82 -12
  53. package/skills/core/editorial-review/references/checklist.md +26 -1
  54. package/skills/core/house-style/SKILL.md +8 -3
  55. package/skills/core/house-style/references/analytical-reporting.md +123 -0
  56. package/skills/core/house-style/references/analytical-writing-patterns.md +79 -0
  57. package/skills/core/house-style/references/analytical-writing-research.md +129 -0
  58. package/skills/core/{write-doc → house-style}/references/bilingual.md +7 -5
  59. package/skills/core/house-style/references/definitions-and-metrics.md +86 -0
  60. package/skills/core/house-style/references/document-workflow.md +193 -0
  61. package/skills/core/house-style/references/initialization.md +66 -0
  62. package/skills/core/house-style/references/persistence.md +9 -4
  63. package/skills/core/house-style/references/rules.md +11 -4
  64. package/skills/core/house-style/scripts/init-guidance.mjs +213 -0
  65. package/skills/core/house-style/templates/analytical-report.md +54 -0
  66. package/skills/core/house-style/templates/gap-analysis.md +1 -1
  67. package/skills/core/plain-language/SKILL.md +2 -2
  68. package/skills/core/polish-cn/SKILL.md +9 -2
  69. package/skills/core/reg-parser/SKILL.md +3 -3
  70. package/skills/core/terminology/SKILL.md +8 -4
  71. package/skills/core/write-doc/SKILL.md +40 -151
  72. package/skills/core/write-report/SKILL.md +129 -0
  73. package/skills/core/{write-doc → write-report}/references/compliance-reports.md +4 -4
  74. package/skills/engineering/better-review/SKILL.md +37 -37
  75. package/skills/engineering/better-review/references/passes.md +35 -41
  76. package/skills/engineering/better-review/references/result.md +10 -9
  77. package/skills/engineering/e2e-test/SKILL.md +17 -17
  78. package/skills/engineering/e2e-test/references/authoring/playwright-config.md +11 -13
  79. package/skills/engineering/e2e-test/references/presentation-sweep.md +7 -7
  80. package/skills/engineering/e2e-test/references/reviewing.md +9 -11
  81. package/skills/engineering/e2e-test/references/route-manifest.md +1 -1
  82. package/skills/engineering/engineering/SKILL.md +124 -0
  83. package/skills/engineering/engineering/references/engineering-conventions.md +32 -0
  84. package/skills/engineering/engineering/references/feature-delivery.md +8 -0
  85. package/skills/engineering/engineering/references/init-scope.md +37 -0
  86. package/skills/engineering/engineering/scripts/init.mjs +160 -0
  87. package/skills/engineering/{contributing → engineering}/scripts/persist-conventions.mjs +1 -1
  88. package/skills/engineering/engineering-runtime/SKILL.md +1 -1
  89. package/skills/engineering/engineering-runtime/coherence/workflow.json +19 -19
  90. package/skills/engineering/engineering-runtime/scripts/workflow-policy.mjs +1 -1
  91. package/skills/engineering/ensure-coverage/SKILL.md +22 -109
  92. package/skills/engineering/ensure-coverage/references/breadth/coverage-ledger.md +7 -5
  93. package/skills/engineering/ensure-coverage/references/breadth/surface-baseline.md +4 -4
  94. package/skills/engineering/ensure-coverage/references/breadth/surface-discovery.md +3 -3
  95. package/skills/engineering/ensure-coverage/references/depth/characterization.md +4 -65
  96. package/skills/engineering/ensure-coverage/references/depth/grading.md +5 -7
  97. package/skills/engineering/ensure-coverage/references/depth/mock-policy.md +6 -12
  98. package/skills/engineering/ensure-coverage/references/enforcement/ci-contract.md +1 -1
  99. package/skills/engineering/ensure-coverage/references/presentation/axis.md +6 -6
  100. package/skills/engineering/ensure-coverage/references/process/audit-mode.md +7 -23
  101. package/skills/engineering/ensure-coverage/references/process/output-template.md +18 -133
  102. package/skills/engineering/ensure-coverage/references/process/test-strategy.md +7 -12
  103. package/skills/engineering/ensure-coverage/scripts/README.md +12 -4
  104. package/skills/engineering/golden-path/SKILL.md +1 -1
  105. package/skills/engineering/harness-runtime/SKILL.md +3 -1
  106. package/skills/engineering/harness-runtime/bin/workspaces.mjs +52 -0
  107. package/skills/engineering/harness-runtime/native-workspace.mjs +239 -0
  108. package/skills/engineering/harness-runtime/references/workspaces.md +78 -0
  109. package/skills/engineering/harness-runtime/workspace-lifecycle.mjs +2154 -0
  110. package/skills/engineering/resolve-issues/SKILL.md +40 -61
  111. package/skills/engineering/resolve-issues/references/ci.md +13 -3
  112. package/skills/engineering/resolve-issues/references/delivery-progress.md +4 -3
  113. package/skills/engineering/resolve-issues/references/done.md +11 -2
  114. package/skills/engineering/resolve-issues/references/expire.md +9 -2
  115. package/skills/engineering/resolve-issues/references/implementation.md +33 -17
  116. package/skills/engineering/resolve-issues/references/preflight.md +3 -1
  117. package/skills/engineering/resolve-issues/references/principles.md +52 -0
  118. package/skills/engineering/resolve-issues/references/review.md +25 -15
  119. package/skills/engineering/resolve-issues/references/task-plan.md +64 -27
  120. package/skills/engineering/resolve-issues/references/workspaces.md +164 -0
  121. package/skills/engineering/resolve-issues/scripts/cleanup-runs.mjs +185 -317
  122. package/skills/engineering/resolve-issues/scripts/next-actions.mjs +44 -7
  123. package/skills/engineering/resolve-issues/scripts/rehydrate.mjs +36 -2
  124. package/skills/engineering/resolve-issues/scripts/review-verdict.mjs +9 -8
  125. package/skills/engineering/resolve-issues/scripts/workspace-lifecycle.mjs +1 -0
  126. package/skills/engineering/resolve-release/SKILL.md +1 -1
  127. package/skills/engineering/rush-issues/SKILL.md +7 -5
  128. package/skills/engineering/rush-release/SKILL.md +1 -1
  129. package/skills/engineering/test-quality/SKILL.md +19 -4
  130. package/skills/engineering/test-quality/references/lint.md +1 -1
  131. package/skills/engineering/test-quality/references/principles.md +2 -2
  132. package/skills/engineering/test-quality/references/testing-conventions.md +1 -1
  133. package/skills/risk-compliance/compliance-audit/SKILL.md +4 -8
  134. package/skills/risk-compliance/compliance-audit/references/audience-and-reports.md +12 -0
  135. package/skills/risk-compliance/contract-compare/SKILL.md +17 -1
  136. package/skills/risk-compliance/contract-review/SKILL.md +6 -1
  137. package/skills/risk-compliance/contract-review/references/report-stage.md +17 -0
  138. package/skills/risk-compliance/doc-authenticity/SKILL.md +11 -1
  139. package/skills/risk-compliance/fraud-detection/LICENSE +3 -0
  140. package/skills/risk-compliance/fraud-detection/SKILL.md +148 -0
  141. package/skills/risk-compliance/{fraud-analysis → fraud-detection}/references/archetypes/first-party-fraud.md +3 -2
  142. package/skills/risk-compliance/fraud-detection/references/archetypes/third-party-fraud.md +47 -0
  143. package/skills/risk-compliance/fraud-detection/references/collection-payout-features.md +151 -0
  144. package/skills/risk-compliance/{fraud-analysis → fraud-detection}/references/contexts/bank-transfer.md +4 -3
  145. package/skills/risk-compliance/fraud-detection/references/contexts/card-payment.md +70 -0
  146. package/skills/risk-compliance/fraud-detection/references/contexts/payment-collection.md +34 -0
  147. package/skills/risk-compliance/fraud-detection/references/contexts/payout.md +34 -0
  148. package/skills/risk-compliance/fraud-detection/references/enrichment.md +74 -0
  149. package/skills/risk-compliance/fraud-detection/references/entities.md +48 -0
  150. package/skills/risk-compliance/{fraud-analysis → fraud-detection}/references/feature-engineering.md +69 -33
  151. package/skills/risk-compliance/fraud-detection/references/feature-sql.md +150 -0
  152. package/skills/risk-compliance/{fraud-analysis → fraud-detection}/references/report-rationale.md +4 -2
  153. package/skills/risk-compliance/{fraud-analysis → fraud-detection}/references/report-template.md +45 -23
  154. package/skills/risk-compliance/{fraud-analysis → fraud-detection}/references/review-checklist.md +60 -20
  155. package/skills/risk-compliance/fraud-detection/references/workflow.md +216 -0
  156. package/skills/risk-compliance/fraud-detection/release-check.mjs +95 -0
  157. package/skills/risk-compliance/payment-analysis/SKILL.md +36 -17
  158. package/skills/risk-compliance/payment-analysis/references/auth-rate-actions.md +2 -2
  159. package/skills/risk-compliance/payment-analysis/references/report-template.md +10 -2
  160. package/skills/risk-compliance/payment-analysis/references/visualization.md +11 -1
  161. package/skills/risk-compliance/portfolio-payment-analysis/LICENSE +3 -0
  162. package/skills/risk-compliance/portfolio-payment-analysis/SKILL.md +170 -0
  163. package/skills/risk-compliance/portfolio-payment-analysis/references/identity-and-reconciliation.md +46 -0
  164. package/skills/risk-compliance/portfolio-payment-analysis/references/metrics-and-reporting.md +170 -0
  165. package/skills/risk-compliance/portfolio-payment-analysis/references/risk-history.md +89 -0
  166. package/skills/risk-compliance/portfolio-payment-analysis/release-check.mjs +95 -0
  167. package/skills/risk-compliance/portfolio-payment-analysis/scripts/analyze.py +636 -0
  168. package/skills/risk-compliance/portfolio-payment-analysis/scripts/build_report.py +386 -0
  169. package/skills/risk-compliance/portfolio-payment-analysis/scripts/comparison_charts.py +425 -0
  170. package/skills/risk-compliance/portfolio-payment-analysis/scripts/csv_export.py +52 -0
  171. package/skills/risk-compliance/portfolio-payment-analysis/scripts/render.py +160 -0
  172. package/skills/risk-compliance/portfolio-payment-analysis/scripts/risk_history.py +435 -0
  173. package/skills/risk-compliance/similar-domain/SKILL.md +9 -4
  174. package/skills/risk-compliance/tld-detection/SKILL.md +124 -239
  175. package/skills/risk-compliance/tld-detection/agents/openai.yaml +1 -1
  176. package/skills/risk-compliance/tld-detection/references/clean.md +18 -51
  177. package/skills/risk-compliance/tld-detection/references/fx-conversion.md +56 -219
  178. package/skills/risk-compliance/tld-detection/references/metric-contract.md +109 -0
  179. package/skills/risk-compliance/tld-detection/references/pattern.md +99 -0
  180. package/skills/risk-compliance/tld-detection/references/report-template.md +49 -272
  181. package/skills/risk-compliance/tld-detection/scripts/detect_ladders.py +46 -13
  182. package/skills/risk-compliance/tld-detection/scripts/detect_patterns.py +346 -0
  183. package/skills/risk-compliance/tld-detection/scripts/detect_streams.py +51 -19
  184. package/skills/risk-compliance/tld-detection/scripts/profile_groups.py +109 -0
  185. package/skills/risk-compliance/tld-detection/scripts/render_charts.py +218 -0
  186. package/skills/risk-compliance/tld-detection/scripts/tld_common.py +243 -0
  187. package/skills/engineering/contributing/SKILL.md +0 -70
  188. package/skills/risk-compliance/fraud-analysis/SKILL.md +0 -114
  189. package/skills/risk-compliance/fraud-analysis/references/archetypes/third-party-fraud.md +0 -27
  190. package/skills/risk-compliance/fraud-analysis/references/contexts/card-payment.md +0 -30
  191. package/skills/risk-compliance/fraud-analysis/references/contexts/payment-collection.md +0 -20
  192. package/skills/risk-compliance/fraud-analysis/references/contexts/payout.md +0 -20
  193. package/skills/risk-compliance/fraud-analysis/references/workflow.md +0 -175
  194. package/skills/risk-compliance/tld-detection/references/chinese-polish.md +0 -55
  195. package/skills/risk-compliance/tld-detection/references/clustering.md +0 -235
  196. package/skills/risk-compliance/tld-detection/references/decision.md +0 -189
  197. package/skills/risk-compliance/tld-detection/references/streams.md +0 -141
  198. package/skills/risk-compliance/tld-detection/references/terminology.md +0 -95
  199. package/skills/risk-compliance/tld-detection/references/workflow.md +0 -95
  200. /package/skills/{engineering/contributing → core/write-report}/LICENSE +0 -0
  201. /package/skills/core/{write-doc → write-report}/references/reports/audit-report-template.md +0 -0
  202. /package/skills/core/{write-doc → write-report}/references/reports/external-assessment-template.md +0 -0
  203. /package/skills/core/{write-doc → write-report}/references/reports/management-report-template.md +0 -0
  204. /package/skills/core/{write-doc → write-report}/references/reports/vars-report-template.md +0 -0
  205. /package/skills/{engineering/contributing → core/write-report}/release-check.mjs +0 -0
  206. /package/skills/{risk-compliance/fraud-analysis → engineering/engineering}/LICENSE +0 -0
  207. /package/skills/engineering/{contributing → engineering}/references/tracker-conventions.md +0 -0
  208. /package/skills/{risk-compliance/fraud-analysis → engineering/engineering}/release-check.mjs +0 -0
  209. /package/skills/engineering/{contributing → engineering}/scripts/persist-conventions-core.mjs +0 -0
  210. /package/skills/risk-compliance/{fraud-analysis → fraud-detection}/references/archetypes/authorized-payment-scam.md +0 -0
  211. /package/skills/risk-compliance/{fraud-analysis → fraud-detection}/references/mechanisms/account-takeover.md +0 -0
  212. /package/skills/risk-compliance/{fraud-analysis → fraud-detection}/references/taxonomy.md +0 -0
  213. /package/skills/risk-compliance/{fraud-analysis → fraud-detection}/references/terminology.md +0 -0
@@ -0,0 +1,170 @@
1
+ ---
2
+ name: portfolio-payment-analysis
3
+ description: >
4
+ Analyze submerchants in Helipay/Worldpay aggregator exports: compare merchants
5
+ and investigate selected merchants' authorization, settlement and disputes,
6
+ including descriptor mapping and overlapping exports. Portfolio-level payment
7
+ overviews belong to payment-analysis; fraud rule discovery belongs to fraud-detection.
8
+ release-version: 0.45.0
9
+ ---
10
+ **Updates:** Once/session run `node <skill-base-dir>/release-check.mjs`.
11
+ # Portfolio payment analysis
12
+
13
+ Before report drafting or substantive review, read
14
+ `{house-style baseDir}/references/analytical-reporting.md` and its
15
+ required writing-pattern and definition references. Use `write-report` for the report stage
16
+ with this skill's merchant template, not `write-doc` or the portfolio report layout. Give
17
+ delegated writers and reviewers the same resolved reference paths and require the reads;
18
+ keep merchant metrics, confidentiality and specialist checks unchanged. Individual native
19
+ selections also need `write-report` and its required `terminology` dependency; installation
20
+ metadata does not load instructions. Missing required resources leave the report stage incomplete.
21
+
22
+ Produce an internal submerchant report in Chinese by default, with merchant comparisons
23
+ and detail for merchants the user selects. Treat the extracts as confidential; do not
24
+ publish them or include cardholder data in the report. Use the installed
25
+ `payment-analysis` skill as the base: read its `SKILL.md` and relevant references for
26
+ periods, event layers, metrics, daily USD FX, disputes, visualization and editorial
27
+ checks. This skill owns the aggregator report structure in
28
+ [metrics and reporting](references/metrics-and-reporting.md); that template replaces
29
+ the base report's chapter order and mandatory Sankey. Inherit the base's metric,
30
+ FX, dispute, terminology and fact-preservation rules. Pass the aggregator template
31
+ to editorial review. Scope any payment-stage evidence to a merchant; do not include a
32
+ portfolio funnel or Sankey.
33
+
34
+ For a clean individual native installation, select `portfolio-payment-analysis`,
35
+ `payment-analysis`, `write-report`, `editorial-review`, `polish-cn`, `terminology`, and `house-style`; the native
36
+ picker does not install dependencies automatically. The generated Payment install
37
+ group recipe includes the dependency closure.
38
+
39
+ ## Workflow
40
+
41
+ 1. Inventory authorized Helipay/Worldpay inputs, source coverage, event dates,
42
+ timezone, currencies, identifiers, field dictionaries and reporting periods.
43
+ Record missing and partial layers. Use the requested period and merchant selection;
44
+ otherwise apply the base skill's period-selection rule, then pass both required
45
+ CLI dates explicitly. Identify an unsupported or unresolved period
46
+ rather than inventing one.
47
+ 2. Read [identity and reconciliation](references/identity-and-reconciliation.md)
48
+ before deduplication or joining. Build the mapping and reconciliation evidence;
49
+ scope every join to the same verified merchant and source namespace. Unknown or
50
+ conflicting identities are not reassigned by descriptor or order similarity.
51
+ 3. Read [metrics and reporting](references/metrics-and-reporting.md). Compute
52
+ merchant rates with merchant-specific denominators and disclose sample counts.
53
+ Include week-by-week comparisons for every submerchant within the report period,
54
+ using Monday–Sunday weeks and explicit partial-week labels. Compare other periods
55
+ for individual merchants when explicitly requested and supported.
56
+ Read [risk history](references/risk-history.md) for 340FRD, dispute histories
57
+ and VAMP. Use the base skill's FX and dispute rules; leave unsupported figures
58
+ unresolved, not zero.
59
+ 4. Present merchant findings, comparison, selected merchant detail and merchant-specific
60
+ investigation actions. Explain missing data, conflicts, unmatched records, rate
61
+ denominators and attribution limits. Keep totals only as internal reconciliation
62
+ evidence; do not report portfolio summaries, trends, decomposition, funnels or
63
+ overall dispute chapters.
64
+ Follow the base skill's editorial review, Chinese polish and fact-preservation
65
+ checks when producing a complete report.
66
+
67
+ ## CLI and scope
68
+
69
+ The bundled workflow uses Python 3 standard-library scripts and local Worldpay CSV
70
+ exports. It makes no network calls. Authorization data is required; settlement and
71
+ dispute files are used when supplied. Run all three commands:
72
+
73
+ ```sh
74
+ python3 {portfolio-payment-analysis baseDir}/scripts/analyze.py --input PATH --output OUTPUT --main-start YYYY-MM-DD --main-end YYYY-MM-DD
75
+ python3 {portfolio-payment-analysis baseDir}/scripts/build_report.py --facts OUTPUT/facts.json --output OUTPUT
76
+ # After editing or polishing presentation.json, rerender without rebuilding its narrative:
77
+ python3 {portfolio-payment-analysis baseDir}/scripts/render.py --model OUTPUT/presentation.json --output OUTPUT
78
+ ```
79
+
80
+ The calculator caps the requested end at the earliest last event date among supplied
81
+ layers. It reports the effective cutoff and compares the corresponding prior-month
82
+ dates. Source event ranges alone do not establish continuous coverage. Check period lengths
83
+ and source coverage before interpreting a comparison.
84
+
85
+ The report outputs are `overview.zh.html` and `overview.zh.md`, backed by the reviewed
86
+ `presentation.json`. Supporting internal files are `facts.json`, `merchant-metrics.csv`,
87
+ `merchant-mapping.csv`, `merchant-weekly.csv`, `merchant-segments.csv`,
88
+ `merchant-detail-comparison.csv`, `merchant-risk-history.csv`, and
89
+ `coverage-and-reconciliation.json`; legacy aggregate fields
90
+ in these files are not report deliverables. The HTML is self-contained, supports
91
+ merchant filtering and printing, and sends no data to external services. Use
92
+ `--detail-merchant ID` on `build_report.py` (repeat it for several IDs) when the user
93
+ names merchants. Otherwise expand the largest merchant by attempts and the lowest-rate
94
+ merchant with at least 30 attempts, while keeping every other merchant available in
95
+ collapsed detail sections. This is a navigation rule, not a significance test.
96
+ Section 2 retains full weekly history. Section 3 uses charts to compare only this week
97
+ with last week, matching weekdays when the current week is partial. Every merchant
98
+ has BIN-country, card-product (payment method × card type), fixed USD amount-bucket,
99
+ authentication and unsuccessful-response charts. Country and card-product charts use
100
+ compact paired bars. Amount buckets use side-by-side histograms, unsuccessful responses
101
+ use side-by-side bars, and authentication uses paired pies for counts and USD amounts,
102
+ not rates. Each pair compares aligned weeks. Use the shared `comparison_charts.py` for
103
+ all report charts. Section 3 omits settlement sales/refunds. Include merchant risk
104
+ history charts as specified in the risk reference. Treat 340FRD file generation date
105
+ as its report date, retaining the earliest date for exact repeats. Monthly dispute
106
+ and fraud charts offer counts and network-style rate estimates with numerator and
107
+ denominator details; weekly charts retain counts. Visa uses same-month sales,
108
+ Mastercard ECP uses prior-month sales, and EFM uses fraud chargebacks divided by
109
+ prior-month e-commerce sales, not all 340FRD Mastercard reports. Fix groups across the union of the
110
+ two comparison periods, and display
111
+ only those two ranges in chart legends and expandable metric-row tables. Follow the
112
+ segment and denominator contract in the reporting reference.
113
+ Include merchant-specific historical refund and dispute follow-ups in the action table
114
+ when supported, without adding portfolio history chapters. If the user says a merchant is
115
+ historical and out of this report, pass `--exclude-merchant ID` (repeat it for several IDs).
116
+ That removes the merchant from comparison, weekly tables, detail, the action list, and every
117
+ linked merchant CSV. State the exclusion once: it is not a closure finding and not missing data.
118
+ Do not lead the report with an excluded merchant. A later rebuild without the flag puts the
119
+ merchant back.
120
+
121
+ The generated lowest-authorization-rate sentence only chooses an authorization review. It is
122
+ not the investigation order. If fraud or predispute history would change who a reader checks
123
+ first, put that merchant and month in the opening, and say whether the month is inside the
124
+ report window. Do not title a real extract 样本报告; 样本 is only for a small attempt count.
125
+
126
+ A packed week cell that includes dollars must say 授权成功 USD. The rule against repeating a
127
+ metric label applies only when the column header already names that measure. When the sales
128
+ column contains both 0.00 and blank, say which merchants have an observed zero and which have
129
+ no settlement layer. An invalid or post-cutoff 340FRD file must state the effect on counts, not
130
+ only the date. Unmatched fraud records must state the count and amount excluded from merchant
131
+ figures.
132
+
133
+ The report includes per-submerchant weekly counts, rates, successful authorization
134
+ amount USD, settled sales, refunds and dispute observations. Each merchant's breakdown
135
+ uses date/week columns and metric rows; successful authorization amount has its own
136
+ row and never substitutes settled sales. Only adjacent full calendar weeks with available observations and valid
137
+ denominators receive week-over-week changes; partial weeks retain their metrics but
138
+ have no week-over-week change. Read the weekly contract in the reporting reference.
139
+
140
+ The optional `--fx-rates` accepts caller-supplied daily USD rates. The CLI does not
141
+ verify their provenance; obtain and preserve Forex Service evidence as specified by
142
+ the base FX contract before relying on converted amounts. Without a required rate,
143
+ the affected amount is unavailable while count metrics remain available. Render unavailable
144
+ cells blank, not N/A; show only `USD 33...` in a USD value cell, without repeating its
145
+ metric label. Remove extra explanatory prose while retaining necessary coverage limits.
146
+
147
+ Source fields remain unchanged in JSON. CSV exports prefix spreadsheet-sensitive
148
+ text with an apostrophe so opening a report does not execute merchant names or
149
+ labels as formulas; numeric metrics remain numeric.
150
+
151
+ Treat internal authorization counters together with `layer_observed.auth`: a zero
152
+ observation count with that flag false is not confirmed zero business activity.
153
+ The report and business CSV cells remain blank in that case. Distinguish observed
154
+ dispute snapshots from deduplicated case-stage counts and verified opening counts;
155
+ they answer different questions and need not match. Formatting-only aliases of a
156
+ verified provider are duplicates, not new snapshots. Sales or refunds without
157
+ stable event identity remain observations, not confirmed monetary totals.
158
+
159
+ The report is an extract-based operational view. The v1 CLI refuses generation if
160
+ any authorization or settlement identity has conflicting values; resolve those
161
+ sources before rerunning. This conservative refusal can block clean periods too.
162
+ It never substitutes totals from an unlabeled clean subset. An absent layer or a
163
+ window without observed settlement/dispute rows produces unavailable metrics, not
164
+ confirmed zero activity. Dispute rows remain observed
165
+ snapshots until opening semantics are verified. The CLI computes supported
166
+ network-style extract estimates, not official network assessments; unsupported rate
167
+ cells stay blank. Merchant-scoped settlement and join evidence must not imply that all
168
+ current-period sales descend from current-period approvals. Review the saved
169
+ `presentation.json` as the narrative source, then rerender both formats. Preserve
170
+ raw customer data in the input project; use synthetic fixtures for repository tests.
@@ -0,0 +1,46 @@
1
+ # Merchant identity and reconciliation
2
+
3
+ ## Identity and mapping
4
+
5
+ Use `Sub merchant ID` as the stable merchant identity, scoped to the verified
6
+ processor/aggregator namespace. Preserve IDs as strings, including leading zeros.
7
+ A descriptor is a display label, not a key: record the source, observed label,
8
+ merchant ID, coverage dates and mapping status. Retain multiple labels for one ID
9
+ and distinguish identical labels belonging to different IDs. Do not merge IDs
10
+ because their descriptors resemble each other. Report absent or unverified IDs in
11
+ an explicit unknown bucket, without attributing them to a named merchant. Expose
12
+ unknown counts and amounts and any mapping conflicts.
13
+
14
+ ## Event grain, overlap and corrections
15
+
16
+ Identify each source's event key and grain from its dictionary before counting:
17
+ authorization attempts, settlement sale/refund events and dispute stage openings
18
+ are different events. Namespace keys by source and merchant where appropriate.
19
+ Keep source paths and snapshot evidence. Deduplicate repeated exports only when
20
+ verified event identity and material values agree. Repeated identical records count
21
+ once. For differing values on one event, use a verified revision sequence or timestamp
22
+ only when the source establishes correction semantics; disclose the restatement.
23
+ Otherwise retain the conflict in reconciliation and mark affected metrics unresolved.
24
+ A missing or ambiguous event key is not permission to collapse rows on order ID,
25
+ amount, date or descriptor. Report raw, unique, duplicate, conflicting and unresolved
26
+ counts per layer and the scope and coverage of each input.
27
+
28
+ ## Join boundaries
29
+
30
+ Join only within the same verified merchant identity and compatible source namespace,
31
+ using the documented event relationship (for example, order ID within merchant for
32
+ an auth-to-sale relationship). A shared order ID alone is not globally unique. Preserve
33
+ one-to-many captures and refunds without multiplying authorization counts; report
34
+ match rates and unmatched or ambiguous records. If an identity or relationship is
35
+ unverified, leave it unjoined and disclose the affected figures. An unknown merchant
36
+ bucket is not a shared identity: do not join unknown records to each other just because
37
+ they share a bucket. Never transfer a case or transaction across merchant boundaries.
38
+
39
+ ## Disputes
40
+
41
+ Use `payment-analysis`'s `references/chargebacks.md`: distinguish stage-opening
42
+ pre-disputes and formal chargebacks from later status updates or repeated snapshots.
43
+ Count distinct verified stage openings, including a verified escalation as a separate
44
+ stage, not as an extra unique case. If stage, opening date, link or revision cannot
45
+ be established, mark affected cells unresolved. Never invent a stage or count status
46
+ updates as new disputes. Keep unclassified cases separate and report coverage.
@@ -0,0 +1,170 @@
1
+ # Metrics and report
2
+
3
+ ## Calculation and coverage
4
+
5
+ Use the installed `payment-analysis` references for formulas, FX, disputes and
6
+ terminology. For each merchant rate, show the merchant-specific numerator,
7
+ denominator, population and dates. A zero denominator is undefined. A known zero
8
+ requires coverage of the relevant period and population; missing layers, unverified
9
+ identity, conflicts and missing historical coverage are not zeros. Show small samples
10
+ with raw counts and a caveat. Do not rank unavailable rates.
11
+
12
+ Keep authorization, settlement, refund and dispute measures separate. Approval is
13
+ not settlement. Scope countries, decline reasons, authentication, settlement and
14
+ disputes to the merchant and the relevant event population. Do not imply that all
15
+ sales in a period descend from approvals in that period. Dispute snapshots are not
16
+ necessarily new openings; apply the base dispute rules and disclose unverified stage,
17
+ opening and coverage. Missing FX leaves affected USD amounts unresolved rather than
18
+ creating mixed-currency totals. Apply the verified 340FRD and dispute history contract
19
+ in [risk history](risk-history.md); do not use those observations as VAMP inputs.
20
+
21
+ For an explicitly requested merchant-specific period comparison, state each date
22
+ range, actual duration, cutoff and coverage. Prior-month endpoints may clamp to the
23
+ month's last day, changing duration. Do not infer a merchant's onboarding or departure
24
+ from observation in only one period. An extract-based comparison is not proof of
25
+ complete coverage or causation. Portfolio totals may support internal reconciliation,
26
+ including the unknown bucket, but are not report content.
27
+
28
+ ## Weekly submerchant comparison
29
+
30
+ Include every Monday–Sunday calendar week intersecting the effective report period
31
+ for every submerchant, including weeks with no observed events. Preserve the full
32
+ calendar boundaries and the included date range. Mark edge weeks shorter than seven
33
+ days as partial; never silently compare a partial week with a full week.
34
+
35
+ Show per-merchant weekly attempts, approvals, approval rate, successful authorization
36
+ amount USD, sales USD, refunds and observed dispute records. Successful authorization
37
+ amount sums `Transaction amount` only where `Response type` is approval, using the
38
+ authorization date and daily USD rates from the base FX contract. Never substitute
39
+ settlement amount. Missing approved amounts, currencies or rates make the affected
40
+ sum unavailable; no auth observations also yield an unavailable sum. Observed auths with no approvals have
41
+ an observed approved amount of zero. Keep the merchant's numerator and denominator together.
42
+ Use authorization time, settlement date and dispute date consistently with the base
43
+ metrics. Missing layer observations or FX make affected measures unavailable, not
44
+ zero growth or confirmed zero activity.
45
+
46
+ Week-over-week changes use only the immediately preceding calendar week. Both weeks
47
+ must be full seven-day bins. Compare only measures whose layer has observations in
48
+ both weeks; relative changes additionally require a positive previous denominator.
49
+ Attempt and sales changes are `(current / previous) - 1`; approval-rate changes are
50
+ `100 * (current rate - previous rate)` percentage points. Do not average merchants,
51
+ bridge a missing week, infer onboarding from a first observation, or report portfolio
52
+ trends. A full calendar week does not prove continuous export coverage: all changes
53
+ remain descriptive comparisons of the supplied observations.
54
+
55
+ ## Merchant detail breakdowns
56
+
57
+ Section 3 provides the same breakdown suite for every merchant, comparing only this
58
+ week with last week. This week is the Monday-based week containing the effective
59
+ cutoff; compare the included weekdays with the same weekdays seven days earlier.
60
+ For example, a Friday cutoff compares Monday–Friday with the preceding Monday–Friday,
61
+ not a five-day period with a seven-day period. Restrict both populations to the
62
+ requested main-period source scope and disclose unavailable earlier observations.
63
+ Show the exact two date ranges in every chart legend and supporting table. Section 2
64
+ continues to own the full weekly history; no main-period-total or older-week columns
65
+ belong in section 3.
66
+
67
+ Charts are the primary presentation, with these fixed layouts:
68
+
69
+ - BIN country and card product: compact paired bar charts; two differently colored
70
+ bars per category compare the weeks for every metric, including rates.
71
+ - Amount buckets: two histograms side by side, one color per week, using the same
72
+ six bins and y-axis scale. Default to count; counts and USD weights can be selected,
73
+ but not approval-rate/share metrics. The unequal/open-ended amount bands are shown
74
+ as equal-width categories, explicitly labeled as binned values rather than density.
75
+ Unknown amounts are listed separately, never drawn as a numeric interval.
76
+ - Unsuccessful response reasons: two bar charts side by side, one color per week,
77
+ with identical category order and scale. Do not re-rank or rescale each week.
78
+ - Authentication: paired pies for the aligned weeks, with count and USD selectors
79
+ only. If any category value is unavailable or negative, do not draw that period's
80
+ pie from an incomplete sum. Keep the supporting cells blank.
81
+
82
+ Do not include settlement sales/refund charts in section 3. Sections 1 and 2 still
83
+ retain their settlement metrics. A metric selector switches supported measures,
84
+ including successful authorization amount USD where applicable. Render unavailable cells
85
+ blank and chart values as gaps, not zeros. Do not repeat a metric label in a cell whose
86
+ column header already names that measure: use `USD 33...`, not `授权成功金额 USD 33...`.
87
+ A packed week cell that also shows attempts and a rate must say `授权成功 USD`, because the
88
+ report also shows settled sales. Use the shared
89
+ `comparison_charts.py` for all report charts. Expandable supporting tables keep metrics as rows and the two periods
90
+ as columns. HTML is self-contained with no external chart service; Markdown retains
91
+ the supporting values.
92
+ Derive groupings only from the merchant's authorized attempts in those two periods;
93
+ do not join settlement amounts into authorization groups.
94
+
95
+ - BIN country: `Issuing bank country`; keep the merchant's top ten by attempts across
96
+ the two comparison periods, `Other` for the rest, and a separate unknown group.
97
+ - Card product: `Payment method` × `Card type`, following payment-analysis. Preserve
98
+ every observed combination and unknown components.
99
+ - Amount bucket: use each attempt's `Transaction amount` converted to USD by its
100
+ authorization date. Fixed half-open ranges are `[0,25)`, `[25,50)`, `[50,100)`,
101
+ `[100,200)`, `[200,500)`, `[500,+inf)`. Missing, nonfinite, negative or unconvertible
102
+ amounts belong to unknown; never silently put them into the zero bucket.
103
+ - Authentication: every observed `Authentication method` value, with unknown separate.
104
+ - Unsuccessful response: code × message among non-approvals only. Keep the merchant's
105
+ top ten reasons across the two comparison periods, Other and unknown. The share denominator is
106
+ that merchant's non-approvals, not all attempts. Unknown responses are not confirmed
107
+ issuer declines or fraud.
108
+
109
+ Freeze group membership from the union of the two comparison periods before calculating each.
110
+ Never re-rank each period independently. Synthetic Other/unknown have distinct keys and display
111
+ labels from literal source strings with those names. For all-attempt groups show
112
+ count, share of merchant attempts, approvals, rate, attempt amount USD and approved
113
+ amount USD. For non-approval reasons show count, share of merchant non-approvals and
114
+ unsuccessful amount USD. Group counts and amounts reconcile to the corresponding
115
+ merchant population; a zero denominator is unavailable, not zero percent.
116
+
117
+ Missing merchant-week observations remain blank. A group absent from an observed
118
+ merchant-week may have zero observed counts, but no approval rate when its count is
119
+ zero. Missing amount or FX invalidates the affected amount sum, not the count.
120
+ Export the two-period group values in `merchant-detail-comparison.csv` for review.
121
+ Add per-merchant dispute and fraud history and monthly VAMP charts using the periods,
122
+ series and availability rules in [risk history](risk-history.md). Use 340FRD file
123
+ generation dates as report dates. Monthly charts switch between counts and rates;
124
+ rate tables and `merchant-risk-history.csv` expose numerator, denominator and its
125
+ month. Keep weekly counts without inventing a weekly monitoring rate. Mastercard
126
+ EFM rates use fraud chargebacks, not the 340FRD count series. These are not
127
+ authorization-cohort metrics. Settlement sales/refunds are omitted from section 3.
128
+
129
+ ## Chinese report structure
130
+
131
+ Use this template for editorial review in place of the base report's chapter order
132
+ and Sankey. Do not add portfolio summary, trends, change decomposition, funnel or
133
+ overall dispute chapters.
134
+
135
+ - Scope header: title, period, effective cutoff, sources and timezone/coverage caveats;
136
+ include a comparison period only when a merchant comparison across periods is requested.
137
+ - 商户要点: merchant-specific findings with counts, denominators and date basis. The lowest authorization rate chooses an authorization review, not the investigation order. If fraud or predispute history would change who is checked first, name that merchant and month here, and say whether the month is inside the report window. A user-excluded historical merchant appears once as an exclusion, not as a finding, and is absent from the tables.
138
+ - 1. 子商户比较: stable IDs and display labels, merchant-level attempts, approvals,
139
+ rates, settlement, refunds and observed disputes where supported. Keep small samples
140
+ visible and unavailable values distinct from zero.
141
+ - 2. 子商户逐周对比: a merchant-by-week matrix of approvals/attempts and rates,
142
+ followed by per-merchant tables with date/week columns horizontally and metrics
143
+ vertically, including successful authorization amount USD as a separate row from
144
+ settled sales. Preserve the same orientation for selected and collapsed merchants.
145
+ Keep all merchants reachable; default detail selections may be expanded while other
146
+ merchant weekly tables are collapsed. Explain partial weeks and unavailable changes.
147
+ - 3. 重点子商户: the full merchant breakdown suite above, using interactive this-week
148
+ versus last-week charts and two-period supporting tables. No report-period total
149
+ or older weeks in the two-week comparisons. Risk history uses its own longer windows.
150
+ Priority merchants are expanded, and all other merchants remain accessible in
151
+ collapsed sections, including when merchants are explicitly selected. Default priority means the largest by attempts and
152
+ the lowest authorization rate among merchants with at least 30 attempts; this is
153
+ a navigation rule, not a significance test. Keep source limitations beside the
154
+ affected merchant and show group denominator definitions once. Remove extra explanatory
155
+ prose; keep only limitations needed to interpret the evidence.
156
+ - 4. 商户行动表: identify the merchant, evidence and next investigation for each row;
157
+ distinguish hypotheses from facts. Include supported historical refund and dispute
158
+ follow-ups for the relevant merchant, not portfolio history.
159
+ - 5. 归因与覆盖: sources, identity, deduplication, conflicts, unknowns, join coverage,
160
+ FX and unresolved attribution limits. Link supporting CSV/JSON reconciliation
161
+ evidence without presenting aggregate totals in the report or exposing cardholder data.
162
+
163
+ ## Done when
164
+
165
+ A reader can identify which merchants to investigate and why, including a stated historical exclusion; each rate identifies
166
+ its merchant, population and period; unsupported data is not presented as zero; and
167
+ merchant attribution does not cross identity boundaries. Internal reconciliation
168
+ accounts for unknowns and conflicts without advertising aggregate fields as deliverables.
169
+ The Markdown and HTML use the same reviewed narrative and separate verified findings
170
+ from operational hypotheses.
@@ -0,0 +1,89 @@
1
+ # Merchant risk history
2
+
3
+ Use the common effective cutoff. Retain 12 calendar months and eight Monday–Sunday
4
+ weeks, with missing periods blank and the final period partial where applicable.
5
+ Every merchant has dispute and fraud counts. Monthly charts also offer a rate view,
6
+ with numerator, denominator and denominator month in the expandable table and CSV.
7
+ Weekly charts show counts: do not invent a weekly card-network monitoring formula.
8
+ All charts use `comparison_charts.py`; nulls are gaps, never fabricated zeros.
9
+
10
+ ## 340FRD reporting date and attribution
11
+
12
+ **Use the DART-340 file generation date as the fraud report date.** This is the
13
+ user-confirmed reporting convention for this adapter. Validate the header date
14
+ against the filename. Deduplicate exact full records across eligible valid files;
15
+ for an exact repeat, use its earliest file generation date. Do not move fraud back
16
+ to the original transaction month or count repeated deliveries again.
17
+
18
+ Validate the v3.5 ASCII header, 17-field details and trailer. Exclude invalid files
19
+ and files generated after the cutoff, recording aggregate evidence. Match ARN plus
20
+ MID only to a unique settled Sale in the verified Worldpay-Acquiring namespace
21
+ (`Worldpay - Acquiring`, whitespace normalized). Original transaction date, currency
22
+ and amount must agree, and the sale must have a resolved submerchant ID. A MID or
23
+ descriptor alone is not a submerchant identity. Preserve unmatched/ambiguous counts
24
+ without exporting raw card data or join identifiers.
25
+
26
+ Full-record variants remain distinct observed records. If variants share an ARN/MID
27
+ and their event identity is unresolved, leave affected fraud-rate cells unavailable;
28
+ do not silently collapse variants or claim that every record is a unique TC40 event.
29
+
30
+ ## Counts and rates are distinct
31
+
32
+ Observed dispute counts group provider, MID, dispute ID and stage, using the earliest
33
+ supplied date for that stage. Updates do not add cases; reversals do not subtract
34
+ incidence. RDR and formal escalation can each appear in their respective series.
35
+ Conflicting identities/brands are quarantined; unknown stages remain unresolved.
36
+
37
+ A monitoring-style chargeback numerator needs an opening and its received date.
38
+ `First CB Request` with `1st chargeback` is the adapter's supported opening pair.
39
+ Response-, loss- or reversal-only cases cannot be promoted to openings. Preserve
40
+ observed counts while leaving affected rate cells blank. Keep independently supported
41
+ merchant/brand/month cells computable.
42
+
43
+ ## Monthly count-rate formulas
44
+
45
+ Scope every numerator and denominator to the same submerchant, brand and verified
46
+ processor namespace. Count settled Sale transactions by their recorded transaction/
47
+ capture month; never use approvals, refunds, or another merchant's sales. Report
48
+ these as **network-style estimates from the extract**, not official identifications.
49
+ Source coverage can be partial and October-style month-to-date results are provisional.
50
+
51
+ | Series | Numerator in report month M | Denominator |
52
+ |---|---|---|
53
+ | Visa Predispute | Observed Visa RDR cases, descriptive only | Visa sales in M |
54
+ | Visa Dispute | Supported Visa formal openings | Visa sales in M |
55
+ | Mastercard chargeback, ECP | Supported Mastercard formal openings | Mastercard sales in M−1 |
56
+ | Visa fraud report rate | Attributable Visa 340FRD reports, dated by file generation | Visa sales in M |
57
+ | Mastercard EFM fraud chargeback rate | Supported fraud chargebacks with reason 4837 or 4863 | Mastercard e-commerce sales in M−1 |
58
+
59
+ The Mastercard fraud **count** chart still shows 340FRD reports. Its EFM **rate** uses
60
+ a different numerator: fraud-related chargebacks, not all 340FRD Mastercard records.
61
+ Label that series explicitly and expose the rate numerator. Unknown reason/channel
62
+ classification or unresolved openings must not silently disappear from a rate.
63
+ Visa Predispute is descriptive and excluded from VAMP.
64
+
65
+ Draw a rate only with an available positive numerator and positive denominator.
66
+ Preserve genuine zero counts, but leave their rate point blank under the base skill's
67
+ point convention. Missing prior-month sales remain missing; use calendar arithmetic
68
+ across year boundaries. Record formulas, denominator dates, status and reason with
69
+ each rate. Do not infer continuous coverage from min/max event dates.
70
+
71
+ ## VAMP
72
+
73
+ The file-generation-date reporting convention resolves the fraud report-date choice.
74
+ Do not continue to list that choice as missing. It does not establish TC40 event
75
+ identity, TC15/TC05 processing dates, corrections, CE3.0/pre-dispute exclusions,
76
+ VisaNet CNP eligibility, completeness or descriptor/acquirer/market grouping.
77
+ Keep official VAMP unavailable until the remaining inputs are verified.
78
+
79
+ VAMP is eligible TC40 fraud plus TC15 disputes divided by TC05 settled transactions
80
+ for the same reporting month. Do not deduplicate across TC40 and TC15. RDR does not
81
+ automatically erase a related TC40. Do not manufacture VAMP by adding the observed
82
+ count series or the descriptive pre-dispute rate.
83
+
84
+ ## Sources
85
+
86
+ - [Stripe monitoring calendars, VAMP, ECP and EFM](https://docs.stripe.com/disputes/monitoring-programs): monthly timing, captured-payment denominators, and EFM fraud-chargeback reasons.
87
+ - [Visa VAMP fact sheet](https://corporate.visa.com/content/dam/VCOM/corporate/visa-perspectives/security-and-trust/documents/visa-acquirer-monitoring-program-fact-sheet-2025.pdf).
88
+ - [Antom monitoring date basis](https://docs.antom.com/ac/dispute/monitor): processor context, not proof of Worldpay processing dates.
89
+ - User-provided DART_340.pdf v3.5 (2021-10-19), §§ 1.1, 5.2, A.2.1–A.2.3, SHA-256 `d7e0b2b01b1f8483ffd78c19b2d289bac17154c15a92c436ca32dbdd4aea6997`. Do not bundle the private PDF, local path or raw data.
@@ -0,0 +1,95 @@
1
+ #!/usr/bin/env node
2
+ import { spawnSync } from 'node:child_process';
3
+ import { mkdirSync, readFileSync, writeFileSync } from 'node:fs';
4
+ import { homedir } from 'node:os';
5
+ import { dirname, join, resolve } from 'node:path';
6
+ import { fileURLToPath } from 'node:url';
7
+
8
+ const DAY_MS = 24 * 60 * 60 * 1000;
9
+ const WEEK_MS = 7 * DAY_MS;
10
+ const here = dirname(fileURLToPath(import.meta.url));
11
+
12
+ function readJson(path, fallback = {}) {
13
+ try { return JSON.parse(readFileSync(path, 'utf8')); } catch { return fallback; }
14
+ }
15
+
16
+ function frontmatterValue(text, key) {
17
+ const frontmatter = /^---\n([\s\S]*?)\n---/.exec(text)?.[1] ?? '';
18
+ const match = new RegExp('^' + key + ':\\s*([^\\n]+)$', 'm').exec(frontmatter);
19
+ return match?.[1].trim().replace(/^['"]|['"]$/g, '') ?? null;
20
+ }
21
+
22
+ function repositoryOf(source) {
23
+ const value = String(source ?? '').trim();
24
+ const match = /^(?:git@github\.com:|https:\/\/github\.com\/)?([A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+?)(?:\.git)?$/.exec(value);
25
+ return match?.[1] ?? null;
26
+ }
27
+
28
+ function stableVersion(value) {
29
+ const match = /^v?(\d+)\.(\d+)\.(\d+)$/.exec(String(value ?? '').trim());
30
+ return match ? match.slice(1).map(Number) : null;
31
+ }
32
+
33
+ function newer(left, right) {
34
+ for (let index = 0; index < 3; index += 1) {
35
+ if (left[index] !== right[index]) return left[index] > right[index];
36
+ }
37
+ return false;
38
+ }
39
+
40
+ function writeCache(path, value) {
41
+ try {
42
+ mkdirSync(dirname(path), { recursive: true });
43
+ writeFileSync(path, JSON.stringify(value));
44
+ } catch { /* A read-only cache must not block skill use. */ }
45
+ }
46
+
47
+ function main(now = Date.now()) {
48
+ if (process.env.ONEABOVEIO_NO_UPDATE_CHECK) return;
49
+ const bundle = readJson(join(resolve(here, '../../..'), 'package.json'));
50
+ if (bundle.name === '@1aboveio/skills' && bundle.nativeCodex?.schemaVersion === 1) return;
51
+ const skill = readFileSync(join(here, 'SKILL.md'), 'utf8');
52
+ const name = frontmatterValue(skill, 'name');
53
+ const localVersion = stableVersion(frontmatterValue(skill, 'release-version'));
54
+ if (!name || !localVersion) return;
55
+
56
+ const lock = readJson(join(process.env.HOME || homedir(), '.agents', '.skill-lock.json'));
57
+ const entry = lock.skills?.[name];
58
+ const repository = repositoryOf(entry?.sourceUrl || entry?.source);
59
+ if (!repository) return;
60
+
61
+ const cacheRoot = process.env.XDG_CACHE_HOME || join(process.env.HOME || homedir(), '.cache');
62
+ const cachePath = join(cacheRoot, '1aboveio-skills', 'release-check.json');
63
+ const all = readJson(cachePath);
64
+ const cache = all[repository] && typeof all[repository] === 'object' ? all[repository] : {};
65
+
66
+ if (!cache.lastCheck || now - cache.lastCheck >= DAY_MS) {
67
+ const result = spawnSync('gh', ['api', 'repos/' + repository + '/releases/latest', '--jq', '.tag_name'], {
68
+ encoding: 'utf8',
69
+ stdio: ['ignore', 'pipe', 'ignore'],
70
+ timeout: 1500,
71
+ });
72
+ cache.lastCheck = now;
73
+ if (result.status === 0 && stableVersion(result.stdout)) cache.latestTag = result.stdout.trim();
74
+ else delete cache.latestTag;
75
+ all[repository] = cache;
76
+ writeCache(cachePath, all);
77
+ }
78
+
79
+ const latestVersion = stableVersion(cache.latestTag);
80
+ if (!latestVersion || !newer(latestVersion, localVersion)) return;
81
+ if (cache.notifiedTag === cache.latestTag && cache.notifiedAt && now - cache.notifiedAt < WEEK_MS) return;
82
+
83
+ cache.notifiedTag = cache.latestTag;
84
+ cache.notifiedAt = now;
85
+ all[repository] = cache;
86
+ writeCache(cachePath, all);
87
+ const command = `npx skills@1.5.23 add '${repository}#${cache.latestTag}' --global --agent universal claude-code --skill ${name} --yes`;
88
+ process.stdout.write(
89
+ `UPDATE_AVAILABLE: A newer 1AboveIO skills release (${cache.latestTag}) is available; this skill is `
90
+ + `v${localVersion.join('.')}. Ask once whether to refresh ${name}. On approval run \`${command}\`. `
91
+ + 'The refreshed instructions apply next session. Either way, continue the current task and do not ask again this session.\n',
92
+ );
93
+ }
94
+
95
+ try { main(); } catch { /* Update checks are advisory and always fail silent. */ }