コミットを比較

...

14 コミット

作成者 SHA1 メッセージ 日付
みてるぞ 53446807c2 #41 ウィニング・ラン修正 2026-06-12 02:08:03 +09:00
みてるぞ 5fbb737c70 Merge remote-tracking branch 'origin/main' into feature/041 2026-06-12 01:35:42 +09:00
みてるぞ def6870f06 グカネータ / 質問パターン見直し (#41) (#365)
Reviewed-on: #365
Co-authored-by: miteruzo <miteruzo@naver.com>
Co-committed-by: miteruzo <miteruzo@naver.com>
2026-06-12 01:35:31 +09:00
みてるぞ a5d08c99cf #41 2026-06-12 01:33:40 +09:00
みてるぞ 2522485f6a Merge remote-tracking branch 'origin/main' into feature/041 2026-06-11 23:58:00 +09:00
みてるぞ de5db81e16 #41 2026-06-11 23:54:55 +09:00
みてるぞ c361c561c2 グカネータ作成 / 質問パターン修正 (#41) (#364)
Reviewed-on: #364
Co-authored-by: miteruzo <miteruzo@naver.com>
Co-committed-by: miteruzo <miteruzo@naver.com>
2026-06-11 23:21:44 +09:00
みてるぞ fd90ef3b15 Merge remote-tracking branch 'origin/main' into feature/041 2026-06-11 23:18:57 +09:00
みてるぞ 4caea6213a #41 少々しやぅ修正 2026-06-11 23:18:37 +09:00
みてるぞ 979ccf598e グカネータ作成 / テスト型バグ修正 (#41) (#363)
Reviewed-on: #363
Co-authored-by: miteruzo <miteruzo@naver.com>
Co-committed-by: miteruzo <miteruzo@naver.com>
2026-06-10 23:43:50 +09:00
みてるぞ 884a7bc3da Merge remote-tracking branch 'origin/main' into feature/041 2026-06-10 23:43:24 +09:00
みてるぞ f936c1e5ce #41 テスト型バグ修正 2026-06-10 23:41:45 +09:00
みてるぞ 37ade2a988 グカネータ作成 (#041) (#362)
Reviewed-on: #362
Co-authored-by: miteruzo <miteruzo@naver.com>
Co-committed-by: miteruzo <miteruzo@naver.com>
2026-06-10 23:33:56 +09:00
みてるぞ 8bf51bbb4a #41 2026-06-10 23:17:12 +09:00
15個のファイルの変更2403行の追加199行の削除
+44 -22
ファイルの表示
@@ -27,26 +27,20 @@ class GekanatorGamesController < ApplicationController
game = GekanatorGame.find_by(id: params[:id])
return head :not_found unless game
asked_ids = Array(game.answers).filter_map { |answer| answer_question_id(answer) }
existing_example_ids =
GekanatorQuestionExample.where(post_id: game.correct_post_id)
.select(:gekanator_question_id)
# Direct examples only for now; post_similarity-based expansion is deferred.
questions =
GekanatorQuestion
.accepted
.includes(:gekanator_question_examples)
.where(kind: 'post_similarity', source: 'user_suggested')
.where.not(id: existing_example_ids)
.order(priority_weight: :desc, id: :asc)
.to_a
selected = weighted_sample_questions(
questions,
post_id: game.correct_post_id,
limit: 2)
render json: {
questions: questions.filter_map { |question|
json = extra_question_json(question)
next if asked_ids.include?(json[:id].to_s)
next if asked_ids.include?("post-similarity:#{ json[:id] }")
json
}.first(2)
questions: selected.map { |question| extra_question_json(question) }
}
end
@@ -84,11 +78,10 @@ class GekanatorGamesController < ApplicationController
gekanator_question: question,
post: game.correct_post,
user: current_user)
example.assign_attributes(
gekanator_game: game,
example.record_answer!(
answer: item[:answer],
source: 'post_game_extra',
weight: 1.0)
gekanator_game: game)
example.save!
end
end
@@ -107,12 +100,41 @@ class GekanatorGamesController < ApplicationController
}
end
def answer_question_id answer
value = if answer.is_a?(Hash)
answer['question_id'].presence || answer[:question_id].presence ||
answer['questionId'].presence || answer[:questionId].presence
def weighted_sample_questions questions, post_id:, limit:
remaining = questions.uniq(&:id)
selected = []
while selected.length < limit && remaining.any?
weighted =
remaining.map { |question|
[question, selection_weight_for(question, post_id: post_id)]
}
total_weight = weighted.sum { |_question, weight| weight }
break if total_weight <= 0
target = rand * total_weight
cumulative = 0.0
chosen =
weighted.find do |_question, weight|
cumulative += weight
cumulative >= target
end&.first || weighted.first.first
selected << chosen
remaining.reject! { |question| question.id == chosen.id }
end
value&.to_s
selected
end
def selection_weight_for question, post_id:
sample_count =
question.gekanator_question_examples.sum { |example|
next 0 unless example.post_id == post_id
example.sample_count.presence || 1
}
question.priority_weight.to_f / (1.0 + sample_count * 0.15)
end
end
+24 -7
ファイルの表示
@@ -16,11 +16,12 @@ class GekanatorQuestionsController < ApplicationController
private
def question_json question
condition = condition_json(question.condition).deep_symbolize_keys
json = {
id: question_id_for(question),
text: question.text,
id: question_id_for(question, condition),
text: question_text_for(question, condition),
kind: question.kind,
condition: condition_json(question.condition),
condition: condition,
source: question.source,
priority_weight: question.priority_weight
}
@@ -30,9 +31,7 @@ class GekanatorQuestionsController < ApplicationController
json
end
def question_id_for question
condition = condition_json(question.condition).deep_symbolize_keys
def question_id_for question, condition
case condition[:type]
when 'tag'
"tag:#{ condition[:key] }"
@@ -44,8 +43,10 @@ class GekanatorQuestionsController < ApplicationController
"original-month:#{ condition[:month] }"
when 'original-month-day'
"original-month-day:#{ condition[:monthDay] || condition[:month_day] }"
when 'title-length-at-least'
"title:length-at-least:#{ condition[:length] }"
when 'title-length-greater-than'
"title:length-greater-than:#{ condition[:length] }"
"title:length-at-least:#{ condition[:length].to_i + 1 }"
when 'title-has-ascii'
'title:ascii'
when 'post-similarity'
@@ -62,9 +63,25 @@ class GekanatorQuestionsController < ApplicationController
json['monthDay'] = json.delete('month_day')
end
if json['type'] == 'title-length-greater-than'
json['type'] = 'title-length-at-least'
json['length'] = json['length'].to_i + 1
end
json
end
def question_text_for question, condition
return question.text unless question.kind == 'title'
case condition[:type]
when 'title-length-at-least'
"タイトルは #{ condition[:length] } 文字以上?"
else
question.text
end
end
def example_answers_json question
question
.gekanator_question_examples
+80
ファイルの表示
@@ -1,5 +1,6 @@
class GekanatorQuestionExample < ApplicationRecord
ANSWERS = GekanatorQuestionSuggestion::ANSWERS
NON_UNKNOWN_ANSWERS = ANSWERS - ['unknown']
SOURCES = ['initial_suggestion', 'post_game_extra'].freeze
belongs_to :gekanator_question
@@ -8,10 +9,89 @@ class GekanatorQuestionExample < ApplicationRecord
belongs_to :gekanator_game, optional: true
validates :answer, presence: true, inclusion: { in: ANSWERS }
validates :answer_counts, presence: true
validates :sample_count,
presence: true,
numericality: {
only_integer: true,
greater_than: 0
}
validates :source, presence: true, inclusion: { in: SOURCES }
validates :weight,
presence: true,
numericality: {
greater_than: 0
}
before_validation :normalize_learning_state
def record_answer!(answer:, source:, gekanator_game: nil)
answer = answer.to_s
raise ArgumentError, 'invalid answer' unless ANSWERS.include?(answer)
counts = normalized_answer_counts
counts[answer] += 1
self.answer_counts = counts
self.sample_count = counts.values.sum
self.gekanator_game = gekanator_game if gekanator_game.present?
self.source = source if new_record?
apply_aggregated_answer!(preferred_answer: answer)
self
end
private
def normalize_learning_state
counts = normalized_answer_counts
if counts.values.sum.zero? && answer.present?
counts[answer] = 1
end
self.answer_counts = counts
self.sample_count = counts.values.sum
apply_aggregated_answer!
end
def apply_aggregated_answer!(preferred_answer: nil)
counts = normalized_answer_counts
known_counts = counts.slice(*NON_UNKNOWN_ANSWERS)
known_total = known_counts.values.sum
if known_total.zero?
self.answer = 'unknown'
self.weight = 0.1
return
else
max_count = known_counts.values.max
candidates = known_counts.select { |_answer, count| count == max_count }.keys
self.answer =
if preferred_answer.present? && candidates.include?(preferred_answer)
preferred_answer
elsif answer.present? && candidates.include?(answer)
answer
else
candidates.first
end
end
consensus = max_count.to_f / known_total
self.weight = Math.sqrt(known_total) * consensus
end
def normalized_answer_counts
base = ANSWERS.index_with(0)
answer_counts.to_h.each do |key, value|
answer_key = key.to_s
next unless ANSWERS.include?(answer_key)
base[answer_key] = value.to_i
end
base
end
end
+9 -6
ファイルの表示
@@ -26,13 +26,16 @@ module Gekanator
},
gekanator_question_suggestion: suggestion,
created_by: user)
GekanatorQuestionExample.create!(
gekanator_question: question,
post: suggestion.gekanator_game.correct_post,
user: user,
gekanator_game: suggestion.gekanator_game,
example =
GekanatorQuestionExample.new(
gekanator_question: question,
post: suggestion.gekanator_game.correct_post,
user: user)
example.record_answer!(
answer: suggestion.answer,
source: 'initial_suggestion')
source: 'initial_suggestion',
gekanator_game: suggestion.gekanator_game)
example.save!
suggestion.update!(processed: true)
question
end
@@ -0,0 +1,40 @@
class AddAnswerStatisticsToGekanatorQuestionExamples < ActiveRecord::Migration[8.0]
class MigrationGekanatorQuestionExample < ApplicationRecord
self.table_name = 'gekanator_question_examples'
end
def up
add_column :gekanator_question_examples,
:answer_counts,
:json,
null: true
add_column :gekanator_question_examples,
:sample_count,
:integer,
null: false,
default: 1
MigrationGekanatorQuestionExample.reset_column_information
MigrationGekanatorQuestionExample.find_each do |example|
counts = {
'yes' => 0,
'no' => 0,
'partial' => 0,
'probably_no' => 0,
'unknown' => 0
}
counts[example.answer] = 1 if counts.key?(example.answer)
example.update_columns(
answer_counts: counts,
sample_count: 1)
end
change_column_null :gekanator_question_examples, :answer_counts, false
end
def down
remove_column :gekanator_question_examples, :sample_count
remove_column :gekanator_question_examples, :answer_counts
end
end
生成ファイル
+3 -1
ファイルの表示
@@ -10,7 +10,7 @@
#
# It's strongly recommended that you check this file into your version control system.
ActiveRecord::Schema[8.0].define(version: 2026_06_10_000000) do
ActiveRecord::Schema[8.0].define(version: 2026_06_12_000000) do
create_table "active_storage_attachments", charset: "utf8mb4", collation: "utf8mb4_0900_ai_ci", force: :cascade do |t|
t.string "name", null: false
t.string "record_type", null: false
@@ -85,6 +85,8 @@ ActiveRecord::Schema[8.0].define(version: 2026_06_10_000000) do
t.float "weight", default: 1.0, null: false
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.json "answer_counts", null: false
t.integer "sample_count", default: 1, null: false
t.index ["gekanator_game_id"], name: "index_gekanator_question_examples_on_gekanator_game_id"
t.index ["gekanator_question_id", "post_id", "user_id"], name: "idx_gekanator_question_examples_on_question_post_user", unique: true
t.index ["gekanator_question_id"], name: "index_gekanator_question_examples_on_gekanator_question_id"
+612
ファイルの表示
@@ -0,0 +1,612 @@
require 'rails_helper'
RSpec.describe 'Gekanator learning API', type: :request do
let(:admin) { create(:user, :admin) }
let(:member) { create(:user, :member) }
let(:other_user) { create(:user, :member) }
let!(:guessed_post) do
Post.create!(
title: 'guessed',
url: 'https://example.com/guessed'
)
end
let!(:correct_post) do
Post.create!(
title: 'correct',
url: 'https://example.com/correct'
)
end
let!(:other_post) do
Post.create!(
title: 'other',
url: 'https://example.com/other'
)
end
let!(:game) do
GekanatorGame.create!(
user: admin,
guessed_post: guessed_post,
correct_post: correct_post,
won: false,
question_count: 1,
answers: [
{
'question_id' => 'tag:character:喜多郁代',
'question_text' => '喜多ちゃんが関係してる?',
'answer' => 'yes',
'original_answer' => 'yes'
}
]
)
end
def create_post_similarity_question!(
text: '喜多ちゃんが泣いてる?',
post: correct_post,
answer: 'yes',
status: 'accepted',
source: 'user_suggested',
priority_weight: 1.2
)
GekanatorQuestion.create!(
text: text,
kind: 'post_similarity',
source: source,
status: status,
priority_weight: priority_weight,
condition: {
type: 'post-similarity',
postId: post.id,
answer: answer,
threshold: 0.65
},
created_by: admin
)
end
describe 'POST /gekanator/games' do
it 'stores a game result for an admin user' do
sign_in_as admin
post '/gekanator/games', params: {
guessed_post_id: guessed_post.id,
correct_post_id: correct_post.id,
answers: [
{
question_id: 'tag:character:喜多郁代',
question_text: '喜多ちゃんが関係してる?',
answer: 'yes',
original_answer: 'yes'
}
]
}
expect(response).to have_http_status(:created)
created = GekanatorGame.find(json['id'])
expect(created.user).to eq(admin)
expect(created.guessed_post).to eq(guessed_post)
expect(created.correct_post).to eq(correct_post)
expect(created.won).to eq(false)
expect(created.question_count).to eq(1)
expect(created.answers).to eq([
{
'question_id' => 'tag:character:喜多郁代',
'question_text' => '喜多ちゃんが関係してる?',
'answer' => 'yes',
'original_answer' => 'yes'
}
])
end
it 'stores a won game when guessed_post_id equals correct_post_id' do
sign_in_as admin
post '/gekanator/games', params: {
guessed_post_id: correct_post.id,
correct_post_id: correct_post.id,
answers: []
}
expect(response).to have_http_status(:created)
expect(GekanatorGame.find(json['id']).won).to eq(true)
end
it 'rejects a game without correct_post_id' do
sign_in_as admin
expect {
post '/gekanator/games', params: {
guessed_post_id: guessed_post.id,
answers: []
}
}.not_to change { GekanatorGame.count }
expect(response).to have_http_status(:unprocessable_entity)
end
it 'returns not found for a non-admin user' do
sign_in_as member
post '/gekanator/games', params: {
guessed_post_id: guessed_post.id,
correct_post_id: correct_post.id,
answers: []
}
expect(response).to have_http_status(:not_found)
end
end
describe 'POST /gekanator/question_suggestions' do
it 'creates a suggestion and promotes yes answer to an accepted post_similarity question' do
sign_in_as admin
expect {
post '/gekanator/question_suggestions', params: {
gekanator_game_id: game.id,
question_text: '喜多ちゃんが泣いてる?',
answer: 'yes'
}
}.to change { GekanatorQuestionSuggestion.count }.by(1)
.and change { GekanatorQuestion.count }.by(1)
.and change { GekanatorQuestionExample.count }.by(1)
expect(response).to have_http_status(:created)
suggestion = GekanatorQuestionSuggestion.last
question = GekanatorQuestion.last
example = GekanatorQuestionExample.last
expect(json).to include(
'id' => suggestion.id,
'count' => 1
)
expect(suggestion).to have_attributes(
gekanator_game_id: game.id,
user_id: admin.id,
question_text: '喜多ちゃんが泣いてる?',
answer: 'yes',
processed: true
)
expect(question).to have_attributes(
text: '喜多ちゃんが泣いてる?',
kind: 'post_similarity',
source: 'user_suggested',
status: 'accepted',
priority_weight: 1.2,
gekanator_question_suggestion_id: suggestion.id,
created_by_id: admin.id
)
expect(question.condition).to include(
'type' => 'post-similarity',
'postId' => correct_post.id,
'answer' => 'yes',
'threshold' => 0.65
)
expect(example).to have_attributes(
gekanator_question_id: question.id,
post_id: correct_post.id,
user_id: admin.id,
gekanator_game_id: game.id,
answer: 'yes',
source: 'initial_suggestion',
weight: 1.0
)
end
it 'promotes no, partial, and probably_no answers' do
sign_in_as admin
['no', 'partial', 'probably_no'].each do |answer|
expect {
post '/gekanator/question_suggestions', params: {
gekanator_game_id: game.id,
question_text: "answer #{answer} question?",
answer: answer
}
}.to change { GekanatorQuestion.count }.by(1)
.and change { GekanatorQuestionExample.count }.by(1)
expect(response).to have_http_status(:created)
expect(GekanatorQuestion.last.condition['answer']).to eq(answer)
expect(GekanatorQuestionExample.last.answer).to eq(answer)
end
end
it 'does not promote unknown answers' do
sign_in_as admin
expect {
post '/gekanator/question_suggestions', params: {
gekanator_game_id: game.id,
question_text: 'よく分からない質問?',
answer: 'unknown'
}
}.to change { GekanatorQuestionSuggestion.count }.by(1)
.and change { GekanatorQuestion.count }.by(0)
.and change { GekanatorQuestionExample.count }.by(0)
expect(response).to have_http_status(:created)
expect(GekanatorQuestionSuggestion.last.processed).to eq(false)
end
it 'limits suggestions to three per game' do
sign_in_as admin
3.times do |i|
GekanatorQuestionSuggestion.create!(
gekanator_game: game,
user: admin,
question_text: "existing question #{i}",
answer: 'unknown'
)
end
expect {
post '/gekanator/question_suggestions', params: {
gekanator_game_id: game.id,
question_text: 'fourth question?',
answer: 'yes'
}
}.not_to change { GekanatorQuestionSuggestion.count }
expect(response).to have_http_status(:unprocessable_entity)
end
it 'returns not found for a non-admin user' do
sign_in_as member
post '/gekanator/question_suggestions', params: {
gekanator_game_id: game.id,
question_text: 'member question?',
answer: 'yes'
}
expect(response).to have_http_status(:not_found)
end
end
describe 'GET /gekanator/games/:id/extra_questions' do
it 'returns at most two accepted user_suggested post_similarity questions without duplicates' do
sign_in_as admin
low = create_post_similarity_question!(
text: 'low?',
priority_weight: 1.0
)
high = create_post_similarity_question!(
text: 'high?',
priority_weight: 3.0
)
middle = create_post_similarity_question!(
text: 'middle?',
priority_weight: 2.0
)
get "/gekanator/games/#{game.id}/extra_questions"
expect(response).to have_http_status(:ok)
expect(json['questions'].length).to eq(2)
expect(json['questions'].map { _1['id'] }.uniq.length).to eq(2)
expect(json['questions'].map { _1['id'] }).to all(be_in([low.id, high.id, middle.id]))
end
it 'can return questions that already have an example for the correct post' do
sign_in_as admin
existing = create_post_similarity_question!(text: 'already learned?')
GekanatorQuestionExample.create!(
gekanator_question: existing,
post: correct_post,
user: admin,
gekanator_game: game,
answer: 'yes',
source: 'post_game_extra'
)
get "/gekanator/games/#{game.id}/extra_questions"
expect(response).to have_http_status(:ok)
expect(json['questions'].map { _1['id'] }).to include(existing.id)
end
it 'can return questions already asked in the game using snake_case question_id' do
sign_in_as admin
asked = create_post_similarity_question!(text: 'already asked?')
game.update!(
answers: [
{
'question_id' => "post-similarity:#{asked.id}",
'answer' => 'yes'
}
]
)
get "/gekanator/games/#{game.id}/extra_questions"
expect(response).to have_http_status(:ok)
expect(json['questions'].map { _1['id'] }).to include(asked.id)
end
it 'can return questions already asked in the game using camelCase questionId' do
sign_in_as admin
asked = create_post_similarity_question!(text: 'already asked?')
game.update!(
answers: [
{
'questionId' => "post-similarity:#{asked.id}",
'answer' => 'yes'
}
]
)
get "/gekanator/games/#{game.id}/extra_questions"
expect(response).to have_http_status(:ok)
expect(json['questions'].map { _1['id'] }).to include(asked.id)
end
it 'does not return non-accepted, non-user_suggested, or non-post_similarity questions' do
sign_in_as admin
accepted = create_post_similarity_question!(text: 'accepted?')
create_post_similarity_question!(text: 'disabled?', status: 'disabled')
create_post_similarity_question!(text: 'ai?', source: 'ai_generated')
GekanatorQuestion.create!(
text: 'tag?',
kind: 'tag',
source: 'user_suggested',
status: 'accepted',
priority_weight: 1.0,
condition: { type: 'tag', key: 'character:喜多郁代' }
)
get "/gekanator/games/#{game.id}/extra_questions"
expect(response).to have_http_status(:ok)
expect(json['questions'].map { _1['id'] }).to contain_exactly(accepted.id)
end
end
describe 'POST /gekanator/games/:id/extra_question_answers' do
it 'creates examples for extra question answers' do
sign_in_as admin
question = create_post_similarity_question!(text: 'extra?')
expect {
post "/gekanator/games/#{game.id}/extra_question_answers", params: {
answers: [
{
question_id: question.id.to_s,
answer: 'partial'
}
]
}
}.to change { GekanatorQuestionExample.count }.by(1)
expect(response).to have_http_status(:created)
expect(json).to include('count' => 1)
example = GekanatorQuestionExample.last
expect(example).to have_attributes(
gekanator_question_id: question.id,
post_id: correct_post.id,
user_id: admin.id,
gekanator_game_id: game.id,
answer: 'partial',
source: 'post_game_extra',
weight: 1.0
)
end
it 'updates an existing example for the same question, post, and user' do
sign_in_as admin
question = create_post_similarity_question!(text: 'extra?')
existing = GekanatorQuestionExample.create!(
gekanator_question: question,
post: correct_post,
user: admin,
answer: 'no',
source: 'post_game_extra',
weight: 1.0
)
expect {
post "/gekanator/games/#{game.id}/extra_question_answers", params: {
answers: [
{
question_id: question.id,
answer: 'yes'
}
]
}
}.not_to change { GekanatorQuestionExample.count }
expect(response).to have_http_status(:created)
expect(existing.reload).to have_attributes(
answer: 'yes',
source: 'post_game_extra',
gekanator_game_id: game.id
)
end
it 'rejects missing questions' do
sign_in_as admin
expect {
post "/gekanator/games/#{game.id}/extra_question_answers", params: {
answers: [
{
question_id: 999_999_999,
answer: 'yes'
}
]
}
}.not_to change { GekanatorQuestionExample.count }
expect(response).to have_http_status(:unprocessable_entity)
end
it 'rejects non-accepted questions' do
sign_in_as admin
question = create_post_similarity_question!(
text: 'disabled?',
status: 'disabled'
)
post "/gekanator/games/#{game.id}/extra_question_answers", params: {
answers: [
{
question_id: question.id,
answer: 'yes'
}
]
}
expect(response).to have_http_status(:unprocessable_entity)
end
it 'rejects non-post_similarity questions' do
sign_in_as admin
question = GekanatorQuestion.create!(
text: 'tag?',
kind: 'tag',
source: 'user_suggested',
status: 'accepted',
priority_weight: 1.0,
condition: { type: 'tag', key: 'character:喜多郁代' }
)
post "/gekanator/games/#{game.id}/extra_question_answers", params: {
answers: [
{
question_id: question.id,
answer: 'yes'
}
]
}
expect(response).to have_http_status(:unprocessable_entity)
end
end
describe 'GET /gekanator/questions' do
it 'returns accepted questions only and includes example_answers for post_similarity questions' do
sign_in_as admin
accepted = create_post_similarity_question!(text: 'accepted?')
create_post_similarity_question!(
text: 'disabled?',
status: 'disabled'
)
GekanatorQuestionExample.create!(
gekanator_question: accepted,
post: correct_post,
user: admin,
answer: 'yes',
source: 'initial_suggestion',
weight: 1.0
)
get '/gekanator/questions'
expect(response).to have_http_status(:ok)
expect(json['questions'].length).to eq(1)
question_json = json['questions'].first
expect(question_json).to include(
'id' => "post-similarity:#{accepted.id}",
'text' => 'accepted?',
'kind' => 'post_similarity',
'source' => 'user_suggested',
'priority_weight' => 1.2
)
expect(question_json['condition']).to include(
'type' => 'post-similarity',
'postId' => correct_post.id,
'answer' => 'yes',
'threshold' => 0.65
)
expect(question_json['example_answers']).to include(
correct_post.id.to_s => 'yes'
)
end
it 'aggregates example_answers by weight' do
sign_in_as admin
question = create_post_similarity_question!(text: 'weighted?')
GekanatorQuestionExample.create!(
gekanator_question: question,
post: other_post,
user: admin,
answer: 'yes',
source: 'post_game_extra',
weight: 1.0
)
GekanatorQuestionExample.create!(
gekanator_question: question,
post: other_post,
user: other_user,
answer: 'no',
source: 'post_game_extra',
weight: 2.0
)
get '/gekanator/questions'
expect(response).to have_http_status(:ok)
question_json = json['questions'].find { _1['id'] == "post-similarity:#{question.id}" }
expect(question_json['example_answers']).to include(
other_post.id.to_s => 'no'
)
end
it 'normalizes legacy title length questions' do
sign_in_as admin
GekanatorQuestion.create!(
text: '題名が長めの投稿?',
kind: 'title',
source: 'admin_curated',
status: 'accepted',
priority_weight: 1.0,
condition: {
type: 'title-length-greater-than',
length: 20
},
created_by: admin
)
get '/gekanator/questions'
expect(response).to have_http_status(:ok)
question_json = json['questions'].find { _1['id'] == 'title:length-at-least:21' }
expect(question_json).to include(
'text' => 'タイトルは 21 文字以上?',
'kind' => 'title'
)
expect(question_json['condition']).to include(
'type' => 'title-length-at-least',
'length' => 21
)
end
end
end
+375
ファイルの表示
@@ -0,0 +1,375 @@
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { apiPost } from '@/lib/api'
import {
buildGekanatorQuestions,
expectedAnswerForQuestion,
restoreGekanatorQuestion,
saveGekanatorExtraQuestionAnswers,
saveGekanatorGame,
saveGekanatorQuestionSuggestion,
} from '@/lib/gekanator'
import type {
GekanatorAnswerLog,
StoredGekanatorQuestion,
} from '@/lib/gekanator'
import type { Post } from '@/types'
vi.mock('@/lib/api', () => ({
apiGet: vi.fn(),
apiPost: vi.fn(),
}))
const mockedApiPost = vi.mocked(apiPost)
const post = (overrides: Partial<Post> = {}): Post => ({
id: 1,
versionNo: 1,
url: 'https://example.com/posts/1',
title: 'post title',
thumbnail: null,
thumbnailBase: null,
tags: [],
viewed: false,
related: [],
originalCreatedFrom: null,
originalCreatedBefore: null,
createdAt: '2026-06-10T00:00:00.000Z',
updatedAt: '2026-06-10T00:00:00.000Z',
uploadedUser: null,
...overrides,
})
describe('expectedAnswerForQuestion', () => {
it('returns a direct example answer when present', () => {
const question: StoredGekanatorQuestion = {
id: 'post-similarity:10',
text: '喜多ちゃんが泣いてる?',
kind: 'post_similarity',
source: 'user_suggested',
priorityWeight: 1.2,
condition: {
type: 'post-similarity',
postId: 999,
answer: 'yes',
threshold: 0.65,
},
exampleAnswers: {
1: 'partial',
},
}
expect(expectedAnswerForQuestion(question, post({ id: 1 }))).toBe('partial')
})
it('returns the condition answer for the original post_similarity post', () => {
const question: StoredGekanatorQuestion = {
id: 'post-similarity:10',
text: '喜多ちゃんが泣いてる?',
kind: 'post_similarity',
source: 'user_suggested',
priorityWeight: 1.2,
condition: {
type: 'post-similarity',
postId: 123,
answer: 'probably_no',
threshold: 0.65,
},
}
expect(expectedAnswerForQuestion(question, post({ id: 123 }))).toBe('probably_no')
})
it('returns null for an unrelated post_similarity post without examples', () => {
const question: StoredGekanatorQuestion = {
id: 'post-similarity:10',
text: '喜多ちゃんが泣いてる?',
kind: 'post_similarity',
source: 'user_suggested',
priorityWeight: 1.2,
condition: {
type: 'post-similarity',
postId: 123,
answer: 'yes',
threshold: 0.65,
},
}
expect(expectedAnswerForQuestion(question, post({ id: 456 }))).toBeNull()
})
it('returns yes for a matching tag question', () => {
const question: StoredGekanatorQuestion = {
id: 'tag:character:喜多郁代',
text: '喜多ちゃんが関係してる?',
kind: 'tag',
condition: {
type: 'tag',
key: 'character:喜多郁代',
},
}
expect(
expectedAnswerForQuestion(
question,
post({
tags: [
{
id: 1,
name: '喜多郁代',
category: 'character',
aliases: [],
parents: [],
postCount: 1,
createdAt: '2026-06-10T00:00:00.000Z',
updatedAt: '2026-06-10T00:00:00.000Z',
hasWiki: false,
hasDeerjikists: false,
materialId: null,
},
],
}),
),
).toBe('yes')
})
it('returns no for a non-matching tag question', () => {
const question: StoredGekanatorQuestion = {
id: 'tag:character:喜多郁代',
text: '喜多ちゃんが関係してる?',
kind: 'tag',
condition: {
type: 'tag',
key: 'character:喜多郁代',
},
}
expect(expectedAnswerForQuestion(question, post({ tags: [] }))).toBe('no')
})
it('ignores example answers for direct title facts', () => {
const question: StoredGekanatorQuestion = {
id: 'title:length-at-least:20',
text: 'タイトルは 20 文字以上?',
kind: 'title',
condition: {
type: 'title-length-at-least',
length: 20,
},
exampleAnswers: {
1: 'yes',
},
}
expect(expectedAnswerForQuestion(question, post({ id: 1, title: 'short' }))).toBe('no')
})
})
describe('restoreGekanatorQuestion', () => {
it('uses default source and priority weight when omitted', () => {
const question = restoreGekanatorQuestion({
id: 'tag:character:喜多郁代',
text: '喜多ちゃんが関係してる?',
kind: 'tag',
condition: {
type: 'tag',
key: 'character:喜多郁代',
},
})
expect(question.source).toBe('default')
expect(question.priorityWeight).toBe(1)
})
it('tests a post_similarity question using direct examples', () => {
const question = restoreGekanatorQuestion({
id: 'post-similarity:10',
text: '喜多ちゃんが泣いてる?',
kind: 'post_similarity',
source: 'user_suggested',
priorityWeight: 1.2,
condition: {
type: 'post-similarity',
postId: 999,
answer: 'yes',
threshold: 0.65,
},
exampleAnswers: {
1: 'yes',
2: 'no',
},
})
expect(question.test(post({ id: 1 }))).toBe(true)
expect(question.test(post({ id: 2 }))).toBe(false)
expect(question.test(post({ id: 3 }))).toBe(false)
})
it('tests a post_similarity question against its configured partial answer', () => {
const question = restoreGekanatorQuestion({
id: 'post-similarity:10',
text: '喜多ちゃんが泣いてる?',
kind: 'post_similarity',
source: 'user_suggested',
priorityWeight: 1.2,
condition: {
type: 'post-similarity',
postId: 999,
answer: 'partial',
threshold: 0.65,
},
exampleAnswers: {
1: 'partial',
2: 'yes',
},
})
expect(question.test(post({ id: 1 }))).toBe(true)
expect(question.test(post({ id: 2 }))).toBe(false)
})
it('normalizes legacy title-length-greater-than questions', () => {
const question = restoreGekanatorQuestion({
id: 'title:length-greater-than:20',
text: '題名が長めの投稿?',
kind: 'title',
condition: {
type: 'title-length-greater-than',
length: 20,
},
})
expect(question.id).toBe('title:length-at-least:21')
expect(question.condition).toEqual({
type: 'title-length-at-least',
length: 21,
})
expect(question.test(post({ title: 'x'.repeat(20) }))).toBe(false)
expect(question.test(post({ title: 'x'.repeat(21) }))).toBe(true)
})
})
describe('buildGekanatorQuestions', () => {
it('builds quantitative title length questions', () => {
const questions = buildGekanatorQuestions([
post({ id: 1, title: 'a' }),
post({ id: 2, title: 'bb' }),
post({ id: 3, title: 'ccc' }),
post({ id: 4, title: 'dddd' }),
])
const titleQuestion = questions.find(question =>
question.condition.type === 'title-length-at-least')
expect(titleQuestion?.text).toMatch(/^タイトルは \d+ 文字以上\?$/)
expect(titleQuestion?.id).toMatch(/^title:length-at-least:\d+$/)
})
})
describe('Gekanator API writers', () => {
beforeEach(() => {
mockedApiPost.mockReset()
})
it('sends game results using snake_case request keys', async () => {
mockedApiPost.mockResolvedValue({ id: 100 })
const answers: GekanatorAnswerLog[] = [
{
questionId: 'tag:character:喜多郁代',
questionText: '喜多ちゃんが関係してる?',
questionCondition: {
type: 'tag',
key: 'character:喜多郁代',
},
answer: 'yes',
originalAnswer: 'partial',
},
]
await expect(
saveGekanatorGame({
guessedPostId: 1,
correctPostId: 2,
answers,
}),
).resolves.toEqual({ id: 100 })
expect(mockedApiPost).toHaveBeenCalledWith('/gekanator/games', {
guessed_post_id: 1,
correct_post_id: 2,
answers: [
{
question_id: 'tag:character:喜多郁代',
question_text: '喜多ちゃんが関係してる?',
question_condition: {
type: 'tag',
key: 'character:喜多郁代',
},
answer: 'yes',
original_answer: 'partial',
},
],
})
})
it('sends question suggestions using snake_case request keys', async () => {
mockedApiPost.mockResolvedValue({
id: 10,
count: 1,
})
await expect(
saveGekanatorQuestionSuggestion({
gekanatorGameId: 100,
questionText: '喜多ちゃんが泣いてる?',
answer: 'yes',
}),
).resolves.toEqual({
id: 10,
count: 1,
})
expect(mockedApiPost).toHaveBeenCalledWith('/gekanator/question_suggestions', {
gekanator_game_id: 100,
question_text: '喜多ちゃんが泣いてる?',
answer: 'yes',
})
})
it('sends extra question answers using snake_case request keys', async () => {
mockedApiPost.mockResolvedValue({
count: 2,
})
await saveGekanatorExtraQuestionAnswers({
gameId: 100,
answers: [
{
questionId: 10,
answer: 'yes',
},
{
questionId: 11,
answer: 'probably_no',
},
],
})
expect(mockedApiPost).toHaveBeenCalledWith(
'/gekanator/games/100/extra_question_answers',
{
answers: [
{
question_id: 10,
answer: 'yes',
},
{
question_id: 11,
answer: 'probably_no',
},
],
},
)
})
})
+94 -13
ファイルの表示
@@ -35,6 +35,7 @@ export type GekanatorQuestionCondition =
| { type: 'original-year'; year: number }
| { type: 'original-month'; month: number }
| { type: 'original-month-day'; monthDay: string }
| { type: 'title-length-at-least'; length: number }
| { type: 'title-length-greater-than'; length: number }
| { type: 'title-has-ascii' }
| {
@@ -44,6 +45,12 @@ export type GekanatorQuestionCondition =
threshold: number
}
type NonPostSimilarityCondition = Exclude<
GekanatorQuestionCondition,
{ type: 'post-similarity' }
>
export type GekanatorExtraQuestion = {
id: number
text: string
@@ -70,10 +77,67 @@ export type GekanatorQuestion = {
test: (post: Post) => boolean }
export const normalizeTitleLengthCondition = (
condition: GekanatorQuestionCondition,
): GekanatorQuestionCondition => {
switch (condition.type)
{
case 'title-length-greater-than':
return {
type: 'title-length-at-least',
length: condition.length + 1 }
default:
return condition
}
}
export const titleLengthMinimumForCondition = (
condition: GekanatorQuestionCondition,
): number | null => {
switch (condition.type)
{
case 'title-length-at-least':
return condition.length
case 'title-length-greater-than':
return condition.length + 1
default:
return null
}
}
export const questionIdForCondition = (
condition: NonPostSimilarityCondition,
): string => {
switch (condition.type)
{
case 'tag':
return `tag:${ condition.key }`
case 'source':
return `source:${ condition.host }`
case 'original-year':
return `original-year:${ condition.year }`
case 'original-month':
return `original-month:${ condition.month }`
case 'original-month-day':
return `original-month-day:${ condition.monthDay }`
case 'title-length-at-least':
case 'title-length-greater-than':
return `title:length-at-least:${ titleLengthMinimumForCondition (condition) }`
case 'title-has-ascii':
return 'title:ascii'
}
}
const directExampleAnswerFor = (
question: StoredGekanatorQuestion,
post: Post,
): GekanatorAnswerValue | null => {
if (question.kind !== 'post_similarity')
return null
const direct = question.exampleAnswers?.[String (post.id) as `${ number }`]
if (direct)
return direct
@@ -222,6 +286,8 @@ const questionMatches = (
return originalMonthOf (post) === question.condition.month
case 'original-month-day':
return originalMonthDayOf (post) === question.condition.monthDay
case 'title-length-at-least':
return (post.title?.length ?? 0) >= question.condition.length
case 'title-length-greater-than':
return (post.title?.length ?? 0) > question.condition.length
case 'title-has-ascii':
@@ -250,6 +316,7 @@ export const expectedAnswerForQuestion = (
case 'original-year':
case 'original-month':
case 'original-month-day':
case 'title-length-at-least':
case 'title-length-greater-than':
case 'title-has-ascii':
return questionMatches (post, question) ? 'yes' : 'no'
@@ -261,20 +328,32 @@ export const expectedAnswerForQuestion = (
export const restoreGekanatorQuestion = (
question: StoredGekanatorQuestion,
): GekanatorQuestion => ({
...question,
source: question.source ?? 'default',
priorityWeight: question.priorityWeight ?? 1,
test: (post: Post) => questionMatches (post, question) })
): GekanatorQuestion => {
const normalizedCondition = normalizeTitleLengthCondition (question.condition)
const normalizedQuestion = {
...question,
id: normalizedCondition.type === 'title-length-at-least'
? `title:length-at-least:${ normalizedCondition.length }`
: question.id,
condition: normalizedCondition,
source: question.source ?? 'default',
priorityWeight: question.priorityWeight ?? 1 }
return {
...normalizedQuestion,
test: (post: Post) => questionMatches (post, normalizedQuestion) }
}
export const storeGekanatorQuestion = (
question: GekanatorQuestion,
): StoredGekanatorQuestion => ({
id: question.id,
id: question.condition.type === 'title-length-greater-than'
? `title:length-at-least:${ question.condition.length + 1 }`
: question.id,
text: question.text,
kind: question.kind,
condition: question.condition,
condition: normalizeTitleLengthCondition (question.condition),
source: question.source,
priorityWeight: question.priorityWeight,
exampleAnswers: question.exampleAnswers })
@@ -293,10 +372,12 @@ export const fetchGekanatorQuestions = async (): Promise<StoredGekanatorQuestion
export const fetchGekanatorExtraQuestions = async (
gameId: number,
gameId: number,
nonce?: string,
): Promise<GekanatorExtraQuestion[]> => {
const data = await apiGet<{ questions: GekanatorExtraQuestion[] }> (
`/gekanator/games/${ gameId }/extra_questions`)
`/gekanator/games/${ gameId }/extra_questions`,
{ params: nonce ? { nonce } : undefined })
return data.questions
}
@@ -402,15 +483,15 @@ export const buildGekanatorQuestions = (posts: Post[]): GekanatorQuestion[] => {
const titleQuestions = [
{
id: 'title:long',
text: '題名が長めの投稿?',
id: `title:length-at-least:${ titleLengthMedian }`,
text: `タイトルは ${ titleLengthMedian } 文字以上?`,
kind: 'title' as const,
condition: {
type: 'title-length-greater-than' as const,
type: 'title-length-at-least' as const,
length: titleLengthMedian },
source: 'default' as const,
priorityWeight: 1,
test: (post: Post) => (post.title?.length ?? 0) > titleLengthMedian },
test: (post: Post) => (post.title?.length ?? 0) >= titleLengthMedian },
{
id: 'title:ascii',
text: '題名に英数字が混じってゐる?',
+151
ファイルの表示
@@ -0,0 +1,151 @@
import { describe, expect, it } from 'vitest'
import {
candidatePostsFor,
hardFilteredPostsForAnswer,
recoverCandidatePosts,
} from '@/lib/gekanatorCandidateRecovery'
import type {
GekanatorAnswerLog,
GekanatorAnswerValue,
GekanatorQuestion,
} from '@/lib/gekanator'
import type { Post } from '@/types'
const post = (id: number): Post => ({
id,
versionNo: 1,
url: `https://example.com/posts/${ id }`,
title: `post ${ id }`,
thumbnail: null,
thumbnailBase: null,
tags: [],
viewed: false,
related: [],
originalCreatedFrom: null,
originalCreatedBefore: null,
createdAt: '2026-06-10T00:00:00.000Z',
updatedAt: '2026-06-10T00:00:00.000Z',
uploadedUser: null,
})
const postSimilarityQuestion = (
id: string,
answers: Record<`${ number }`, GekanatorAnswerValue>,
): GekanatorQuestion => ({
id,
text: `${ id }?`,
kind: 'post_similarity',
condition: {
type: 'post-similarity',
postId: 9999,
answer: 'yes',
threshold: 0.65 },
source: 'user_suggested',
priorityWeight: 1,
exampleAnswers: answers,
test: candidate => answers[String (candidate.id) as `${ number }`] === 'yes',
})
const answer = (
question: GekanatorQuestion,
value: GekanatorAnswerValue,
): GekanatorAnswerLog => ({
questionId: question.id,
questionText: question.text,
questionCondition: question.condition,
answer: value,
originalAnswer: value,
})
describe('candidatePostsFor', () => {
it('lets recovered candidates ignore old answers but not later answers', () => {
const posts = [post (1), post (2), post (3)]
const oldQuestion = postSimilarityQuestion ('old', {
1: 'no',
2: 'yes',
3: 'yes',
})
const laterQuestion = postSimilarityQuestion ('later', {
1: 'no',
2: 'no',
3: 'yes',
})
const candidates = candidatePostsFor ({
posts,
questions: [oldQuestion, laterQuestion],
answers: [answer (oldQuestion, 'yes'), answer (laterQuestion, 'yes')],
softenedQuestionIds: new Set (),
rejectedPostIds: new Set (),
recoveredCandidatePosts: new Map ([
[1, 1],
[3, 1],
]) })
expect(candidates.map (candidate => candidate.id)).toEqual ([3])
})
it('does not let recovered candidates bypass explicit rejected posts', () => {
const posts = [post (1), post (2)]
const question = postSimilarityQuestion ('question', {
1: 'yes',
2: 'yes',
})
const candidates = candidatePostsFor ({
posts,
questions: [question],
answers: [answer (question, 'yes')],
softenedQuestionIds: new Set (),
rejectedPostIds: new Set ([1]),
recoveredCandidatePosts: new Map ([[1, 1]]) })
expect(candidates.map (candidate => candidate.id)).toEqual ([2])
})
})
describe('hardFilteredPostsForAnswer', () => {
it('returns zero candidates without falling back to the original pool', () => {
const posts = [post (1), post (2)]
const question = postSimilarityQuestion ('question', {
1: 'yes',
2: 'yes',
})
expect(hardFilteredPostsForAnswer ({
posts,
question,
answer: 'no',
})).toEqual ([])
})
})
describe('recoverCandidatePosts', () => {
it('recovers high-score non-rejected, non-eligible candidates in staged batches', () => {
const posts = Array.from ({ length: 10 }, (_value, index) => post (index + 1))
const scores = new Map (posts.map (candidate => [candidate.id, candidate.id]))
const recovered = recoverCandidatePosts ({
posts,
scores,
rejectedPostIds: new Set ([10]),
recoveredCandidatePosts: new Map ([[8, 1]]),
eligiblePostIds: new Set ([9]),
answerCountAtRecovery: 2,
recoveryStepCount: 0,
})
expect(recovered?.recoveryStepCount).toBe (1)
expect([...(recovered?.recoveredCandidatePosts.keys () ?? [])])
.toEqual ([8, 7, 6, 5, 4, 3, 2])
expect(recovered?.recoveredCandidatePosts.get (7)).toBe (2)
})
})
+146
ファイルの表示
@@ -0,0 +1,146 @@
import { expectedAnswerForQuestion } from '@/lib/gekanator'
import type {
GekanatorAnswerLog,
GekanatorAnswerValue,
GekanatorQuestion,
} from '@/lib/gekanator'
import type { Post } from '@/types'
export type RecoveredCandidatePost = {
postId: number
answerCountAtRecovery: number }
export const candidatePostsFor = ({
posts,
questions,
answers,
softenedQuestionIds,
rejectedPostIds,
recoveredCandidatePosts,
}: {
posts: Post[]
questions: GekanatorQuestion[]
answers: GekanatorAnswerLog[]
softenedQuestionIds: Set<string>
rejectedPostIds: Set<number>
recoveredCandidatePosts: Map<number, number>
}): Post[] => {
const questionById = new Map (questions.map (question => [question.id, question]))
return posts.filter (post => {
if (rejectedPostIds.has (post.id))
return false
const answerCountAtRecovery = recoveredCandidatePosts.get (post.id)
return answers.every ((answer, index) => {
if (answerCountAtRecovery !== undefined && index < answerCountAtRecovery)
return true
if (softenedQuestionIds.has (answer.questionId))
return true
const question = questionById.get (answer.questionId)
if (!(question))
return true
switch (answer.answer)
{
case 'yes':
case 'no': {
const expected = expectedAnswerForQuestion (question, post)
return expected === null || expected === 'unknown' || expected === answer.answer
}
default:
return true
}
})
})
}
export const hardFilteredPostsForAnswer = ({
posts,
question,
answer,
}: {
posts: Post[]
question: GekanatorQuestion
answer: GekanatorAnswerValue
}): Post[] => {
if (answer === 'unknown')
return posts
return posts.filter (post => {
const expected = expectedAnswerForQuestion (question, post)
return expected === null || expected === 'unknown' || expected === answer
})
}
const concreteAnswerOptions: GekanatorAnswerValue[] = [
'yes',
'no',
'partial',
'probably_no']
export const allConcreteAnswerOptionsExhausted = (
posts: Post[],
question: GekanatorQuestion | null,
): boolean => {
if (!(question))
return false
return concreteAnswerOptions.every (answer =>
hardFilteredPostsForAnswer ({ posts, question, answer }).length === 0)
}
const nextRecoveryBatchSize = (recoveryStepCount: number): number =>
6 * (2 ** recoveryStepCount)
export const recoverCandidatePosts = ({
posts,
scores,
rejectedPostIds,
recoveredCandidatePosts,
eligiblePostIds,
answerCountAtRecovery,
recoveryStepCount,
}: {
posts: Post[]
scores: Map<number, number>
rejectedPostIds: Set<number>
recoveredCandidatePosts: Map<number, number>
eligiblePostIds: Set<number>
answerCountAtRecovery: number
recoveryStepCount: number
}): {
recoveredCandidatePosts: Map<number, number>
recoveryStepCount: number
} | null => {
const recovered = new Map (recoveredCandidatePosts)
const candidates = posts
.filter (post =>
!(rejectedPostIds.has (post.id))
&& !(eligiblePostIds.has (post.id))
&& !(recovered.has (post.id)))
.sort ((a, b) =>
(scores.get (b.id) ?? Number.NEGATIVE_INFINITY)
- (scores.get (a.id) ?? Number.NEGATIVE_INFINITY))
.slice (0, nextRecoveryBatchSize (recoveryStepCount))
if (candidates.length === 0)
return null
candidates.forEach (post => recovered.set (post.id, answerCountAtRecovery))
return {
recoveredCandidatePosts: recovered,
recoveryStepCount: recoveryStepCount + 1 }
}
+167
ファイルの表示
@@ -0,0 +1,167 @@
import { titleLengthMinimumForCondition } from '@/lib/gekanator'
import type {
GekanatorAnswerLog,
GekanatorAnswerValue,
GekanatorQuestion,
} from '@/lib/gekanator'
export const monthForCondition = (
condition: GekanatorQuestion['condition'],
): number | null => {
if (condition.type === 'original-month')
return condition.month
if (condition.type !== 'original-month-day')
return null
const month = Number (condition.monthDay.split ('-')[0])
return Number.isInteger (month) ? month : null
}
const isTitleLengthContradiction = (
candidate: GekanatorQuestion['condition'],
previous: GekanatorQuestion['condition'],
answer: GekanatorAnswerValue,
): boolean => {
const candidateLength = titleLengthMinimumForCondition (candidate)
const previousLength = titleLengthMinimumForCondition (previous)
if (candidateLength === null || previousLength === null)
return false
switch (answer)
{
case 'yes':
return candidateLength <= previousLength
case 'no':
return candidateLength >= previousLength
default:
return false
}
}
const isQuestionRedundantAfterAnswers = (
question: GekanatorQuestion,
answers: GekanatorAnswerLog[],
): boolean => answers.some (answer => {
const previous = answer.questionCondition
return previous !== undefined
&& isTitleLengthContradiction (question.condition, previous, answer.answer)
})
const isSourceFactBlocked = (
candidate: GekanatorQuestion['condition'],
previous: GekanatorQuestion['condition'],
answer: GekanatorAnswerValue,
): boolean => {
if (candidate.type !== 'source' || previous.type !== 'source')
return false
switch (answer)
{
case 'yes':
return true
case 'no':
return candidate.host === previous.host
default:
return false
}
}
const isOriginalYearFactBlocked = (
candidate: GekanatorQuestion['condition'],
previous: GekanatorQuestion['condition'],
answer: GekanatorAnswerValue,
): boolean => {
if (candidate.type !== 'original-year' || previous.type !== 'original-year')
return false
switch (answer)
{
case 'yes':
return true
case 'no':
return candidate.year === previous.year
default:
return false
}
}
const isOriginalMonthFactBlocked = (
candidate: GekanatorQuestion['condition'],
previous: GekanatorQuestion['condition'],
answer: GekanatorAnswerValue,
): boolean => {
switch (answer)
{
case 'yes':
if (previous.type === 'original-month')
{
if (candidate.type === 'original-month')
return true
if (candidate.type === 'original-month-day')
return monthForCondition (candidate) !== previous.month
return false
}
if (previous.type === 'original-month-day')
return candidate.type === 'original-month'
|| candidate.type === 'original-month-day'
return false
case 'no':
if (previous.type === 'original-month')
{
if (candidate.type === 'original-month')
return candidate.month === previous.month
if (candidate.type === 'original-month-day')
return monthForCondition (candidate) === previous.month
return false
}
if (previous.type === 'original-month-day')
return candidate.type === 'original-month-day'
&& candidate.monthDay === previous.monthDay
return false
default:
return false
}
}
const isFactQuestionBlocked = (
candidate: GekanatorQuestion['condition'],
previous: GekanatorQuestion['condition'],
answer: GekanatorAnswerValue,
): boolean => {
if (!(answer === 'yes' || answer === 'no'))
return false
return isSourceFactBlocked (candidate, previous, answer)
|| isOriginalYearFactBlocked (candidate, previous, answer)
|| isOriginalMonthFactBlocked (candidate, previous, answer)
}
export const isQuestionHardFilteredAfterAnswers = (
question: GekanatorQuestion,
answers: GekanatorAnswerLog[],
): boolean => answers.some (answer => {
const previous = answer.questionCondition
if (previous === undefined)
return false
return isQuestionRedundantAfterAnswers (question, [answer])
|| isFactQuestionBlocked (question.condition, previous, answer.answer)
})
+2 -2
ファイルの表示
@@ -12,8 +12,8 @@ export const gekanatorKeys = {
root: ['gekanator'] as const,
posts: () => ['gekanator', 'posts'] as const,
questions: () => ['gekanator', 'questions'] as const,
extraQuestions: (gameId: number) =>
['gekanator', 'games', gameId, 'extra-questions'] as const }
extraQuestions: (gameId: number, nonce: string) =>
['gekanator', 'games', gameId, 'extra-questions', nonce] as const }
export const tagsKeys = {
root: ['tags'] as const,
+154
ファイルの表示
@@ -0,0 +1,154 @@
import { describe, expect, it } from 'vitest'
import { isQuestionHardFilteredAfterAnswers } from '@/lib/gekanatorQuestionFilters'
import type {
GekanatorAnswerLog,
GekanatorAnswerValue,
GekanatorQuestion,
GekanatorQuestionCondition,
} from '@/lib/gekanator'
const question = (
condition: GekanatorQuestionCondition,
): GekanatorQuestion => ({
id: `${ condition.type }:candidate`,
text: 'candidate?',
kind: condition.type === 'source'
? 'source'
: condition.type.startsWith ('original-')
? 'original_date'
: condition.type.startsWith ('title-')
? 'title'
: 'tag',
condition,
source: 'default',
priorityWeight: 1,
test: () => false,
})
const answer = (
condition: GekanatorQuestionCondition,
value: GekanatorAnswerValue,
): GekanatorAnswerLog => ({
questionId: 'previous',
questionText: 'previous?',
questionCondition: condition,
answer: value,
originalAnswer: value,
})
const blocked = (
candidate: GekanatorQuestionCondition,
previous: GekanatorQuestionCondition,
value: GekanatorAnswerValue,
): boolean =>
isQuestionHardFilteredAfterAnswers (question (candidate), [answer (previous, value)])
describe('isQuestionHardFilteredAfterAnswers', () => {
it('blocks only contradictory or redundant month questions after a yes answer', () => {
const previous: GekanatorQuestionCondition = { type: 'original-month', month: 12 }
expect(blocked ({ type: 'original-month', month: 12 }, previous, 'yes')).toBe(true)
expect(blocked ({ type: 'original-month', month: 2 }, previous, 'yes')).toBe(true)
expect(blocked ({ type: 'original-month-day', monthDay: '2-14' }, previous, 'yes'))
.toBe(true)
expect(blocked ({ type: 'original-month-day', monthDay: '12-25' }, previous, 'yes'))
.toBe(false)
expect(blocked ({ type: 'original-year', year: 2024 }, previous, 'yes')).toBe(false)
expect(blocked ({ type: 'source', host: 'example.com' }, previous, 'yes')).toBe(false)
expect(blocked ({ type: 'tag', key: 'character:喜多郁代' }, previous, 'yes')).toBe(false)
})
it('blocks same-month facts after a no answer', () => {
const previous: GekanatorQuestionCondition = { type: 'original-month', month: 12 }
expect(blocked ({ type: 'original-month', month: 12 }, previous, 'no')).toBe(true)
expect(blocked ({ type: 'original-month', month: 2 }, previous, 'no')).toBe(false)
expect(blocked ({ type: 'original-month-day', monthDay: '12-25' }, previous, 'no'))
.toBe(true)
expect(blocked ({ type: 'original-month-day', monthDay: '2-14' }, previous, 'no'))
.toBe(false)
})
it('blocks all month and month-day questions after a month-day yes answer', () => {
const previous: GekanatorQuestionCondition = {
type: 'original-month-day',
monthDay: '12-25',
}
expect(blocked ({ type: 'original-month', month: 12 }, previous, 'yes')).toBe(true)
expect(blocked ({ type: 'original-month', month: 2 }, previous, 'yes')).toBe(true)
expect(blocked ({ type: 'original-month-day', monthDay: '12-25' }, previous, 'yes'))
.toBe(true)
expect(blocked ({ type: 'original-month-day', monthDay: '12-26' }, previous, 'yes'))
.toBe(true)
})
it('blocks the same month-day only after a month-day no answer', () => {
const previous: GekanatorQuestionCondition = {
type: 'original-month-day',
monthDay: '12-25',
}
expect(blocked ({ type: 'original-month-day', monthDay: '12-25' }, previous, 'no'))
.toBe(true)
expect(blocked ({ type: 'original-month-day', monthDay: '12-26' }, previous, 'no'))
.toBe(false)
expect(blocked ({ type: 'original-month', month: 12 }, previous, 'no')).toBe(false)
})
it('blocks year and source as single-value facts', () => {
expect(blocked (
{ type: 'original-year', year: 2025 },
{ type: 'original-year', year: 2024 },
'yes',
)).toBe(true)
expect(blocked (
{ type: 'original-year', year: 2024 },
{ type: 'original-year', year: 2024 },
'no',
)).toBe(true)
expect(blocked (
{ type: 'source', host: 'b.example' },
{ type: 'source', host: 'a.example' },
'yes',
)).toBe(true)
expect(blocked (
{ type: 'source', host: 'b.example' },
{ type: 'source', host: 'a.example' },
'no',
)).toBe(false)
})
it('does not hard-filter partial, probably_no, or unknown fact answers', () => {
const previous: GekanatorQuestionCondition = { type: 'original-month', month: 12 }
const candidate: GekanatorQuestionCondition = { type: 'original-month', month: 2 }
expect(blocked (candidate, previous, 'partial')).toBe(false)
expect(blocked (candidate, previous, 'probably_no')).toBe(false)
expect(blocked (candidate, previous, 'unknown')).toBe(false)
})
it('keeps title-length hard redundancy for yes and no only', () => {
const previous: GekanatorQuestionCondition = {
type: 'title-length-at-least',
length: 30,
}
expect(blocked ({ type: 'title-length-at-least', length: 20 }, previous, 'yes'))
.toBe(true)
expect(blocked ({ type: 'title-length-at-least', length: 40 }, previous, 'yes'))
.toBe(false)
expect(blocked ({ type: 'title-length-at-least', length: 40 }, previous, 'no'))
.toBe(true)
expect(blocked ({ type: 'title-length-at-least', length: 20 }, previous, 'no'))
.toBe(false)
expect(blocked ({ type: 'title-length-at-least', length: 20 }, previous, 'partial'))
.toBe(false)
})
})
+502 -148
ファイルの表示
@@ -10,11 +10,19 @@ import { buildGekanatorQuestions,
fetchGekanatorExtraQuestions,
fetchGekanatorQuestions,
fetchGekanatorPosts,
normalizeTitleLengthCondition,
restoreGekanatorQuestion,
saveGekanatorExtraQuestionAnswers,
saveGekanatorGame,
saveGekanatorQuestionSuggestion,
storeGekanatorQuestion } from '@/lib/gekanator'
storeGekanatorQuestion,
titleLengthMinimumForCondition } from '@/lib/gekanator'
import { allConcreteAnswerOptionsExhausted,
candidatePostsFor,
hardFilteredPostsForAnswer,
recoverCandidatePosts } from '@/lib/gekanatorCandidateRecovery'
import { isQuestionHardFilteredAfterAnswers,
monthForCondition } from '@/lib/gekanatorQuestionFilters'
import { gekanatorKeys } from '@/lib/queryKeys'
import { cn } from '@/lib/utils'
@@ -23,8 +31,10 @@ import type { FC } from 'react'
import type { GekanatorAnswerLog,
GekanatorAnswerValue,
GekanatorExtraQuestion,
GekanatorQuestionCondition,
GekanatorQuestion,
StoredGekanatorQuestion } from '@/lib/gekanator'
import type { RecoveredCandidatePost } from '@/lib/gekanatorCandidateRecovery'
import type { Post } from '@/types'
type Phase =
@@ -60,12 +70,16 @@ type GameSnapshot = {
answers: GekanatorAnswerLog[]
askedIds: Set<string>
softenedQuestionIds: Set<string>
recoveredCandidatePosts: Map<number, number>
recoveryStepCount: number
askedQuestionBank: GekanatorQuestion[]
search: string
selectingCorrectPost: boolean
rejectedPostIds: Set<number>
lastGuessQuestionCount: number
lastRejectedGuessId: number | null
winningRunTargetId: number | null
winningRunStartAnswerCount: number | null
activeGuessId: number | null
reviewGuessedPostId: number | null
reviewCorrectPostId: number | null }
@@ -76,6 +90,8 @@ type StoredGekanatorGame = {
answers: GekanatorAnswerLog[]
askedIds: string[]
softenedQuestionIds: string[]
recoveredCandidatePosts?: RecoveredCandidatePost[]
recoveryStepCount?: number
askedQuestionBank?: StoredGekanatorQuestion[]
askedQuestionBankIds?: string[]
search: string
@@ -85,6 +101,8 @@ type StoredGekanatorGame = {
rejectedPostIds: number[]
lastGuessQuestionCount: number
lastRejectedGuessId: number | null
winningRunTargetId?: number | null
winningRunStartAnswerCount?: number | null
activeGuessId: number | null
reviewGuessedPostId: number | null
reviewCorrectPostId: number | null
@@ -112,6 +130,7 @@ const minQuestionsBeforeCertainGuess = 5
const certainGuessPercent = 99.5
const runnerUpMaxPercent = .5
const hardMaxQuestions = 80
const winningRunQuestionLimit = 3
const softenedAnswerWeight = .35
const confidenceTemperature = 6
const gameStorageKey = 'gekanator:game:v1'
@@ -144,6 +163,50 @@ const createGameSeed = (): string => {
}
const normalizeStoredQuestionId = (
questionId: string,
condition?: GekanatorQuestionCondition,
): string => {
if (condition?.type === 'title-length-greater-than')
return `title:length-at-least:${ condition.length + 1 }`
if (questionId.startsWith ('title:length-greater-than:'))
{
const length = Number (questionId.split (':').pop ())
if (Number.isInteger (length))
return `title:length-at-least:${ length + 1 }`
}
return questionId
}
const normalizeStoredGame = (game: StoredGekanatorGame): StoredGekanatorGame => ({
...game,
answers: game.answers.map (answer => ({
...answer,
questionId: normalizeStoredQuestionId (
answer.questionId,
answer.questionCondition),
questionCondition: answer.questionCondition
? normalizeTitleLengthCondition (answer.questionCondition)
: undefined })),
askedIds: game.askedIds.map (questionId => normalizeStoredQuestionId (questionId)),
softenedQuestionIds: game.softenedQuestionIds.map (questionId =>
normalizeStoredQuestionId (questionId)),
recoveredCandidatePosts: game.recoveredCandidatePosts ?? [],
recoveryStepCount: game.recoveryStepCount ?? 0,
winningRunTargetId: game.winningRunTargetId ?? null,
winningRunStartAnswerCount: game.winningRunStartAnswerCount ?? null,
askedQuestionBank: game.askedQuestionBank?.map (question =>
({
...question,
id: normalizeStoredQuestionId (question.id, question.condition),
condition: normalizeTitleLengthCondition (question.condition) })),
askedQuestionBankIds: game.askedQuestionBankIds?.map (questionId =>
normalizeStoredQuestionId (questionId)) })
const sourcePriorityForMerge = (question: GekanatorQuestion): number => {
switch (question.source)
{
@@ -214,7 +277,7 @@ const loadStoredGame = (): StoredGekanatorGame | null => {
if (!(raw))
return null
return JSON.parse (raw) as StoredGekanatorGame
return normalizeStoredGame (JSON.parse (raw) as StoredGekanatorGame)
}
catch
{
@@ -237,6 +300,20 @@ const resettableExtraQuestionState = (): {
extraQuestionState: 'idle' })
const recoveredCandidateMapFromStored = (
items: RecoveredCandidatePost[],
): Map<number, number> =>
new Map (items.map (item => [item.postId, item.answerCountAtRecovery]))
const storedRecoveredCandidatesFromMap = (
recoveredCandidatePosts: Map<number, number>,
): RecoveredCandidatePost[] =>
[...recoveredCandidatePosts.entries ()].map (([postId, answerCountAtRecovery]) => ({
postId,
answerCountAtRecovery }))
const deltaFor = (matched: boolean, answer: GekanatorAnswerValue): number => {
switch (answer)
{
@@ -356,48 +433,6 @@ const recalculateScores = ({
}
const candidatePostsFor = ({
posts,
questions,
answers,
softenedQuestionIds,
rejectedPostIds,
}: {
posts: Post[]
questions: GekanatorQuestion[]
answers: GekanatorAnswerLog[]
softenedQuestionIds: Set<string>
rejectedPostIds: Set<number>
}): Post[] => {
const questionById = new Map (questions.map (question => [question.id, question]))
return posts.filter (post => {
if (rejectedPostIds.has (post.id))
return false
return answers.every (answer => {
if (softenedQuestionIds.has (answer.questionId))
return true
const question = questionById.get (answer.questionId)
if (!(question))
return true
switch (answer.answer)
{
case 'yes':
case 'no': {
const expected = expectedAnswerForQuestion (question, post)
return expected === null || expected === 'unknown' || expected === answer.answer
}
default:
return true
}
})
})
}
const confidencesFor = (posts: Post[], scores: Map<number, number>): Confidence[] => {
if (posts.length === 0)
return []
@@ -446,17 +481,18 @@ const previewAnswer = ({
question: GekanatorQuestion
answer: GekanatorAnswerValue
}): AnswerPreview => {
const hardFilteredPosts =
answer === 'unknown'
? posts
: posts.filter (post => {
const expected = expectedAnswerForQuestion (question, post)
return expected === null || expected === 'unknown' || expected === answer
})
const nextPosts =
hardFilteredPosts.length > 0
? hardFilteredPosts
: posts
const nextPosts = hardFilteredPostsForAnswer ({
posts,
question,
answer })
if (nextPosts.length === 0)
return {
answer,
top: null,
candidateCount: 0,
effectiveCandidates: 0,
entropy: 0 }
const nextScores = new Map (scores)
nextPosts.forEach (post => {
const expected = expectedAnswerForQuestion (question, post)
@@ -548,6 +584,13 @@ const sameConditionValue = (
left: GekanatorQuestion['condition'],
right: GekanatorQuestion['condition'],
): boolean => {
const leftTitleLength = titleLengthMinimumForCondition (left)
const rightTitleLength = titleLengthMinimumForCondition (right)
if (leftTitleLength !== null || rightTitleLength !== null)
return leftTitleLength !== null
&& rightTitleLength !== null
&& leftTitleLength === rightTitleLength
if (left.type !== right.type)
return false
@@ -564,12 +607,13 @@ const sameConditionValue = (
return String (condition.month)
case 'original-month-day':
return condition.monthDay
case 'title-length-greater-than':
return String (condition.length)
case 'title-has-ascii':
return ''
case 'post-similarity':
return `${ condition.postId }:${ condition.answer }:${ condition.threshold }`
case 'title-length-at-least':
case 'title-length-greater-than':
return String (titleLengthMinimumForCondition (condition) ?? '')
}
}
@@ -577,20 +621,6 @@ const sameConditionValue = (
}
const monthForCondition = (
condition: GekanatorQuestion['condition'],
): number | null => {
if (condition.type === 'original-month')
return condition.month
if (condition.type !== 'original-month-day')
return null
const month = Number (condition.monthDay.split ('-')[0])
return Number.isInteger (month) ? month : null
}
const isMonthCrossMatch = (
candidate: GekanatorQuestion['condition'],
previous: GekanatorQuestion['condition'],
@@ -725,6 +755,9 @@ const chooseQuestion = ({
return questionsToRank
.map (question => {
if (isQuestionHardFilteredAfterAnswers (question, answers))
return null
const signature = signatureFor (question, candidates)
if (redundant.has (signature))
return null
@@ -802,6 +835,135 @@ const chooseQuestion = ({
}
const directWinningRunExampleAnswerFor = (
question: GekanatorQuestion,
targetPost: Post,
): GekanatorAnswerValue | null =>
question.kind !== 'post_similarity'
? null
: question.exampleAnswers?.[String (targetPost.id) as `${ number }`] ?? null
const winningRunPriorityFor = (
question: GekanatorQuestion,
expected: GekanatorAnswerValue,
targetPost: Post,
): number | null => {
if (question.kind === 'post_similarity')
{
const directAnswer = directWinningRunExampleAnswerFor (question, targetPost)
if (directAnswer === null)
return null
if (expected === 'yes')
return 1
if (expected === 'no')
return 3
return null
}
if (expected === 'yes')
return 0
if (expected === 'no')
return 2
return null
}
const chooseWinningRunQuestion = ({
posts,
fallbackPosts,
questions,
targetPost,
scores,
answers,
askedIds,
gameSeed,
}: {
posts: Post[]
fallbackPosts: Post[]
questions: GekanatorQuestion[]
targetPost: Post
scores: Map<number, number>
answers: GekanatorAnswerLog[]
askedIds: Set<string>
gameSeed: string
}): GekanatorQuestion | null => {
const ranked = questions
.filter (question => {
if (askedIds.has (question.id))
return false
if (isQuestionHardFilteredAfterAnswers (question, answers))
return false
const expected = expectedAnswerForQuestion (question, targetPost)
return expected !== null && expected !== 'unknown'
})
.map (question => {
const expected = expectedAnswerForQuestion (question, targetPost)
const priority =
expected === null
? null
: winningRunPriorityFor (question, expected, targetPost)
if (priority === null)
return null
const yesCount = posts.filter (post => question.test (post)).length
const matchingCount =
expected === 'yes' || expected === 'partial'
? yesCount
: posts.length - yesCount
return {
question,
priority,
matchingCount }
})
.filter ((item): item is {
question: GekanatorQuestion
priority: number
matchingCount: number } => item !== null)
.sort ((a, b) => {
if (a.priority !== b.priority)
return a.priority - b.priority
if (a.matchingCount !== b.matchingCount)
return a.matchingCount - b.matchingCount
if (a.question.priorityWeight !== b.question.priorityWeight)
return b.question.priorityWeight - a.question.priorityWeight
return a.question.id.localeCompare (b.question.id)
})
if (ranked.length > 0)
return ranked[0]?.question ?? null
return chooseQuestion ({
posts: fallbackPosts.length > 0 ? fallbackPosts : posts,
questions,
scores,
answers,
askedIds,
gameSeed })
}
const isWinningRunActive = (
winningRunTargetId: number | null,
winningRunStartAnswerCount: number | null,
): boolean =>
winningRunTargetId !== null && winningRunStartAnswerCount !== null
const winningRunQuestionCount = (
answers: GekanatorAnswerLog[],
winningRunStartAnswerCount: number | null,
): number => winningRunStartAnswerCount === null
? 0
: Math.max (0, answers.length - winningRunStartAnswerCount)
const bestPost = (posts: Post[], scores: Map<number, number>): Post | null =>
posts
.map (post => ({ post, score: scores.get (post.id) ?? 0 }))
@@ -848,6 +1010,10 @@ const GekanatorPage: FC = () => {
() => new Set (storedGame?.askedIds ?? []))
const [softenedQuestionIds, setSoftenedQuestionIds] = useState<Set<string>> (
() => new Set (storedGame?.softenedQuestionIds ?? []))
const [recoveredCandidatePosts, setRecoveredCandidatePosts] = useState<Map<number, number>> (
() => recoveredCandidateMapFromStored (storedGame?.recoveredCandidatePosts ?? []))
const [recoveryStepCount, setRecoveryStepCount] = useState (
storedGame?.recoveryStepCount ?? 0)
const [askedQuestionBank, setAskedQuestionBank] = useState<GekanatorQuestion[]> (
() => (storedGame?.askedQuestionBank ?? []).map (restoreGekanatorQuestion))
const [storedAskedQuestionBankIds, setStoredAskedQuestionBankIds] = useState<string[]> (
@@ -866,6 +1032,10 @@ const GekanatorPage: FC = () => {
storedGame?.lastGuessQuestionCount ?? 0)
const [lastRejectedGuessId, setLastRejectedGuessId] = useState<number | null> (
storedGame?.lastRejectedGuessId ?? null)
const [winningRunTargetId, setWinningRunTargetId] = useState<number | null> (
storedGame?.winningRunTargetId ?? null)
const [winningRunStartAnswerCount, setWinningRunStartAnswerCount] =
useState<number | null> (storedGame?.winningRunStartAnswerCount ?? null)
const [activeGuessId, setActiveGuessId] = useState<number | null> (
storedGame?.activeGuessId ?? null)
const [reviewGuessedPostId, setReviewGuessedPostId] = useState<number | null> (
@@ -938,6 +1108,8 @@ const GekanatorPage: FC = () => {
answers,
askedIds: [...askedIds],
softenedQuestionIds: [...softenedQuestionIds],
recoveredCandidatePosts: storedRecoveredCandidatesFromMap (recoveredCandidatePosts),
recoveryStepCount,
askedQuestionBank: askedQuestionBank.map (storeGekanatorQuestion),
askedQuestionBankIds: storedAskedQuestionBankIds,
search,
@@ -947,6 +1119,8 @@ const GekanatorPage: FC = () => {
rejectedPostIds: [...rejectedPostIds],
lastGuessQuestionCount,
lastRejectedGuessId,
winningRunTargetId,
winningRunStartAnswerCount,
activeGuessId,
reviewGuessedPostId,
reviewCorrectPostId,
@@ -973,6 +1147,8 @@ const GekanatorPage: FC = () => {
answers,
askedIds,
softenedQuestionIds,
recoveredCandidatePosts,
recoveryStepCount,
askedQuestionBank,
storedAskedQuestionBankIds,
search,
@@ -982,6 +1158,8 @@ const GekanatorPage: FC = () => {
rejectedPostIds,
lastGuessQuestionCount,
lastRejectedGuessId,
winningRunTargetId,
winningRunStartAnswerCount,
activeGuessId,
reviewGuessedPostId,
reviewCorrectPostId,
@@ -1000,8 +1178,10 @@ const GekanatorPage: FC = () => {
questions: askedQuestionBank,
answers,
softenedQuestionIds,
rejectedPostIds }),
[posts, askedQuestionBank, answers, softenedQuestionIds, rejectedPostIds])
rejectedPostIds,
recoveredCandidatePosts }),
[posts, askedQuestionBank, answers, softenedQuestionIds,
rejectedPostIds, recoveredCandidatePosts])
const questions = useMemo (
() => mergeQuestions ([
...buildGekanatorQuestions (eligiblePosts.length > 1 ? eligiblePosts : posts),
@@ -1014,27 +1194,51 @@ const GekanatorPage: FC = () => {
() => new Map (scoringQuestions.map (question => [question.id, question])),
[scoringQuestions])
const questionsSinceLastGuess = answers.length - lastGuessQuestionCount
const nonRejectedPosts = useMemo (
const availablePosts = useMemo (
() => posts.filter (post => !(rejectedPostIds.has (post.id))),
[posts, rejectedPostIds])
const winningRunTargetPost = useMemo (
() => winningRunTargetId === null
? null
: posts.find (post => post.id === winningRunTargetId) ?? null,
[posts, winningRunTargetId])
const winningRunQuestionsAsked = winningRunQuestionCount (
answers,
winningRunStartAnswerCount)
const winningRunActive =
isWinningRunActive (winningRunTargetId, winningRunStartAnswerCount)
&& winningRunQuestionsAsked < winningRunQuestionLimit
&& eligiblePosts.length === 1
&& eligiblePosts[0]?.id === winningRunTargetId
&& winningRunTargetPost !== null
const questionPosts =
eligiblePosts.length > 1
|| questionsSinceLastGuess >= minQuestionsBeforeCertainGuess
? eligiblePosts
: nonRejectedPosts
: availablePosts
const topScoredPosts = useMemo (
() => eligiblePosts
.map (post => ({ post, score: scores.get (post.id) ?? 0 }))
.sort ((a, b) => b.score - a.score)
.slice (0, 3),
[eligiblePosts, scores])
const currentQuestion = chooseQuestion ({
posts: questionPosts,
questions: scoringQuestions,
scores,
answers,
askedIds,
gameSeed })
const currentQuestion = winningRunActive && winningRunTargetPost
? chooseWinningRunQuestion ({
posts,
fallbackPosts: availablePosts.length > 1 ? availablePosts : posts,
questions: scoringQuestions,
targetPost: winningRunTargetPost,
scores,
answers,
askedIds,
gameSeed })
: chooseQuestion ({
posts: questionPosts,
questions: scoringQuestions,
scores,
answers,
askedIds,
gameSeed })
const answerPreviews = useMemo (
() => currentQuestion
? answerOptions.map (option => previewAnswer ({
@@ -1047,7 +1251,7 @@ const GekanatorPage: FC = () => {
const guessablePosts =
eligiblePosts.length > 0
? eligiblePosts
: nonRejectedPosts
: availablePosts
const guess = bestPost (guessablePosts, scores)
const displayedGuess =
posts.find (post => post.id === activeGuessId) ?? guess
@@ -1095,6 +1299,8 @@ const GekanatorPage: FC = () => {
setAnswers ([])
setAskedIds (new Set ())
setSoftenedQuestionIds (new Set ())
setRecoveredCandidatePosts (new Map ())
setRecoveryStepCount (0)
setAskedQuestionBank ([])
setSearch ('')
setSelectingCorrectPost (false)
@@ -1103,6 +1309,8 @@ const GekanatorPage: FC = () => {
setRejectedPostIds (new Set ())
setLastGuessQuestionCount (0)
setLastRejectedGuessId (null)
setWinningRunTargetId (null)
setWinningRunStartAnswerCount (null)
setActiveGuessId (null)
setReviewGuessedPostId (null)
setReviewCorrectPostId (null)
@@ -1121,14 +1329,26 @@ const GekanatorPage: FC = () => {
nextAskedQuestionBank,
nextSoftenedQuestionIds,
nextRejectedPostIds,
nextRecoveredCandidatePosts,
nextRecoveryStepCount,
allowPreQuestionRecovery,
}: {
nextAnswers: GekanatorAnswerLog[]
nextAskedIds: Set<string>
nextAskedQuestionBank: GekanatorQuestion[]
nextSoftenedQuestionIds: Set<string>
nextRejectedPostIds: Set<number>
nextRecoveredCandidatePosts: Map<number, number>
nextRecoveryStepCount: number
allowPreQuestionRecovery?: boolean
}) => {
let recoveredSoftenedQuestionIds = new Set (nextSoftenedQuestionIds)
let recoveredCandidatePosts = new Map (nextRecoveredCandidatePosts)
let recoveredStepCount = nextRecoveryStepCount
const answerCountAtRecovery =
allowPreQuestionRecovery
? nextAnswers.length
: Math.max (nextAnswers.length - 1, 0)
let recoveredScores = recalculateScores ({
posts,
questions: nextAskedQuestionBank,
@@ -1139,27 +1359,72 @@ const GekanatorPage: FC = () => {
questions: nextAskedQuestionBank,
answers: nextAnswers,
softenedQuestionIds: recoveredSoftenedQuestionIds,
rejectedPostIds: nextRejectedPostIds })
rejectedPostIds: nextRejectedPostIds,
recoveredCandidatePosts })
let recoveredScoringQuestions = mergeQuestions ([
...buildGekanatorQuestions (
recoveredEligiblePosts.length > 1 ? recoveredEligiblePosts : posts),
...acceptedQuestions,
...nextAskedQuestionBank])
while (
recoveredEligiblePosts.length === 0
|| (
recoveredEligiblePosts.length !== 1
&& !(chooseQuestion ({
posts: recoveredEligiblePosts,
questions: recoveredScoringQuestions,
scores: recoveredScores,
answers: nextAnswers,
askedIds: nextAskedIds,
gameSeed })))
)
const refreshRecoveredState = () => {
recoveredScores = recalculateScores ({
posts,
questions: nextAskedQuestionBank,
answers: nextAnswers,
softenedQuestionIds: recoveredSoftenedQuestionIds })
recoveredEligiblePosts = candidatePostsFor ({
posts,
questions: nextAskedQuestionBank,
answers: nextAnswers,
softenedQuestionIds: recoveredSoftenedQuestionIds,
rejectedPostIds: nextRejectedPostIds,
recoveredCandidatePosts })
recoveredScoringQuestions = mergeQuestions ([
...buildGekanatorQuestions (
recoveredEligiblePosts.length > 1 ? recoveredEligiblePosts : posts),
...acceptedQuestions,
...nextAskedQuestionBank])
}
const needsPreQuestionRecovery = () => {
if (!(allowPreQuestionRecovery) || recoveredEligiblePosts.length === 0)
return false
const nextQuestion = chooseQuestion ({
posts: recoveredEligiblePosts,
questions: recoveredScoringQuestions,
scores: recoveredScores,
answers: nextAnswers,
askedIds: nextAskedIds,
gameSeed })
return allConcreteAnswerOptionsExhausted (recoveredEligiblePosts, nextQuestion)
}
while (recoveredEligiblePosts.length === 0 || needsPreQuestionRecovery ())
{
if (nextAnswers.length >= hardMaxQuestions)
const recoveredPosts = recoverCandidatePosts ({
posts,
scores: recoveredScores,
rejectedPostIds: nextRejectedPostIds,
recoveredCandidatePosts,
eligiblePostIds: new Set (recoveredEligiblePosts.map (post => post.id)),
answerCountAtRecovery,
recoveryStepCount: recoveredStepCount })
if (recoveredPosts)
{
recoveredCandidatePosts = recoveredPosts.recoveredCandidatePosts
recoveredStepCount = recoveredPosts.recoveryStepCount
refreshRecoveredState ()
if (recoveredEligiblePosts.length > 0 && !(needsPreQuestionRecovery ()))
break
}
if (
recoveredEligiblePosts.length > 0
|| nextAnswers.length >= hardMaxQuestions
)
break
const softened = softenNextQuestionIds ({
@@ -1170,26 +1435,13 @@ const GekanatorPage: FC = () => {
break
recoveredSoftenedQuestionIds = softened
recoveredScores = recalculateScores ({
posts,
questions: nextAskedQuestionBank,
answers: nextAnswers,
softenedQuestionIds: recoveredSoftenedQuestionIds })
recoveredEligiblePosts = candidatePostsFor ({
posts,
questions: nextAskedQuestionBank,
answers: nextAnswers,
softenedQuestionIds: recoveredSoftenedQuestionIds,
rejectedPostIds: nextRejectedPostIds })
recoveredScoringQuestions = mergeQuestions ([
...buildGekanatorQuestions (
recoveredEligiblePosts.length > 1 ? recoveredEligiblePosts : posts),
...acceptedQuestions,
...nextAskedQuestionBank])
refreshRecoveredState ()
}
return {
softenedQuestionIds: recoveredSoftenedQuestionIds,
recoveredCandidatePosts,
recoveryStepCount: recoveredStepCount,
scores: recoveredScores,
eligiblePosts: recoveredEligiblePosts,
scoringQuestions: recoveredScoringQuestions }
@@ -1209,12 +1461,16 @@ const GekanatorPage: FC = () => {
answers: [...answers],
askedIds: new Set (askedIds),
softenedQuestionIds: new Set (softenedQuestionIds),
recoveredCandidatePosts: new Map (recoveredCandidatePosts),
recoveryStepCount,
askedQuestionBank: [...askedQuestionBank],
search,
selectingCorrectPost,
rejectedPostIds: new Set (rejectedPostIds),
lastGuessQuestionCount,
lastRejectedGuessId,
winningRunTargetId,
winningRunStartAnswerCount,
activeGuessId,
reviewGuessedPostId,
reviewCorrectPostId }])
@@ -1233,21 +1489,42 @@ const GekanatorPage: FC = () => {
nextAskedIds,
nextAskedQuestionBank,
nextSoftenedQuestionIds: softenedQuestionIds,
nextRejectedPostIds: rejectedPostIds })
nextRejectedPostIds: rejectedPostIds,
nextRecoveredCandidatePosts: recoveredCandidatePosts,
nextRecoveryStepCount: recoveryStepCount })
const nextSoftenedQuestionIds = recovered.softenedQuestionIds
const nextRecoveredCandidatePosts = recovered.recoveredCandidatePosts
const nextScores = recovered.scores
const nextEligiblePosts = recovered.eligiblePosts
const currentWinningRunActive =
isWinningRunActive (winningRunTargetId, winningRunStartAnswerCount)
const nextWinningRunTargetId =
nextEligiblePosts.length === 1
? nextEligiblePosts[0]?.id ?? null
: null
const nextWinningRunStartAnswerCount =
nextWinningRunTargetId === null
? null
: currentWinningRunActive
&& winningRunTargetId === nextWinningRunTargetId
&& winningRunStartAnswerCount !== null
? winningRunStartAnswerCount
: nextAnswers.length
setScores (nextScores)
setAskedIds (nextAskedIds)
setSoftenedQuestionIds (nextSoftenedQuestionIds)
setRecoveredCandidatePosts (nextRecoveredCandidatePosts)
setRecoveryStepCount (recovered.recoveryStepCount)
setAskedQuestionBank (nextAskedQuestionBank)
setAnswers (nextAnswers)
setWinningRunTargetId (nextWinningRunTargetId)
setWinningRunStartAnswerCount (nextWinningRunStartAnswerCount)
const nextGuessablePosts =
nextEligiblePosts.length > 0
? nextEligiblePosts
: nonRejectedPosts
: availablePosts
const nextGuess = bestPost (nextGuessablePosts, nextScores)
const nextQuestionCount = answers.length + 1
const nextQuestionsSinceLastGuess =
@@ -1256,6 +1533,13 @@ const GekanatorPage: FC = () => {
const topConfidence = nextConfidences[0] ?? null
const runnerUpConfidence = nextConfidences[1] ?? null
const structurallyCertain = nextEligiblePosts.length === 1
const winningRunContinues =
nextWinningRunTargetId !== null
&& nextWinningRunStartAnswerCount !== null
&& nextEligiblePosts.length === 1
&& winningRunQuestionCount (
nextAnswers,
nextWinningRunStartAnswerCount) < winningRunQuestionLimit
const statisticallyCertain =
topConfidence !== null
&& topConfidence.percent >= certainGuessPercent
@@ -1268,8 +1552,9 @@ const GekanatorPage: FC = () => {
&& (structurallyCertain || statisticallyCertain)
const shouldGuess =
nextQuestionCount >= hardMaxQuestions
|| canGuessByQuestionCount
|| canGuessEarlyByConfidence
|| (
!(winningRunContinues)
&& (canGuessByQuestionCount || canGuessEarlyByConfidence))
if (shouldGuess)
{
setActiveGuessId (nextGuess?.id ?? null)
@@ -1383,6 +1668,12 @@ const GekanatorPage: FC = () => {
}
setRejectedPostIds (new Set ([...rejectedPostIds, displayedGuess.id]))
setRecoveredCandidatePosts (
new Map (
[...recoveredCandidatePosts.entries ()].filter (
([postId]) => postId !== displayedGuess.id)))
setWinningRunTargetId (null)
setWinningRunStartAnswerCount (null)
setActiveGuessId (null)
setSearch ('')
setSelectingCorrectPost (false)
@@ -1400,12 +1691,16 @@ const GekanatorPage: FC = () => {
setAnswers (snapshot.answers)
setAskedIds (snapshot.askedIds)
setSoftenedQuestionIds (snapshot.softenedQuestionIds)
setRecoveredCandidatePosts (snapshot.recoveredCandidatePosts)
setRecoveryStepCount (snapshot.recoveryStepCount)
setAskedQuestionBank (snapshot.askedQuestionBank)
setSearch (snapshot.search)
setSelectingCorrectPost (snapshot.selectingCorrectPost)
setRejectedPostIds (snapshot.rejectedPostIds)
setLastGuessQuestionCount (snapshot.lastGuessQuestionCount)
setLastRejectedGuessId (snapshot.lastRejectedGuessId)
setWinningRunTargetId (snapshot.winningRunTargetId)
setWinningRunStartAnswerCount (snapshot.winningRunStartAnswerCount)
setActiveGuessId (snapshot.activeGuessId)
setReviewGuessedPostId (snapshot.reviewGuessedPostId)
setReviewCorrectPostId (snapshot.reviewCorrectPostId)
@@ -1421,20 +1716,63 @@ const GekanatorPage: FC = () => {
nextAskedIds: askedIds,
nextAskedQuestionBank: askedQuestionBank,
nextSoftenedQuestionIds: softenedQuestionIds,
nextRejectedPostIds: rejectedPostIds })
nextRejectedPostIds: rejectedPostIds,
nextRecoveredCandidatePosts: recoveredCandidatePosts,
nextRecoveryStepCount: recoveryStepCount,
allowPreQuestionRecovery: true })
setSoftenedQuestionIds (recovered.softenedQuestionIds)
setRecoveredCandidatePosts (recovered.recoveredCandidatePosts)
setRecoveryStepCount (recovered.recoveryStepCount)
setScores (recovered.scores)
const nextWinningRunTargetId =
recovered.eligiblePosts.length === 1
? recovered.eligiblePosts[0]?.id ?? null
: null
const nextWinningRunStartAnswerCount =
nextWinningRunTargetId === null
? null
: isWinningRunActive (winningRunTargetId, winningRunStartAnswerCount)
&& winningRunTargetId === nextWinningRunTargetId
&& winningRunStartAnswerCount !== null
? winningRunStartAnswerCount
: answers.length
const nextWinningRunTargetPost =
nextWinningRunTargetId === null
? null
: posts.find (post => post.id === nextWinningRunTargetId) ?? null
const nextQuestion = chooseQuestion ({
posts: recovered.eligiblePosts.length > 1
? recovered.eligiblePosts
: nonRejectedPosts,
questions: recovered.scoringQuestions,
scores: recovered.scores,
answers,
askedIds,
gameSeed })
const recoveredGuessablePosts =
recovered.eligiblePosts.length > 0
? recovered.eligiblePosts
: availablePosts
const nextQuestion =
nextWinningRunTargetPost
&& nextWinningRunStartAnswerCount !== null
&& winningRunQuestionCount (
answers,
nextWinningRunStartAnswerCount) < winningRunQuestionLimit
? chooseWinningRunQuestion ({
posts,
fallbackPosts: availablePosts.length > 1 ? availablePosts : posts,
questions: recovered.scoringQuestions,
targetPost: nextWinningRunTargetPost,
scores: recovered.scores,
answers,
askedIds,
gameSeed })
: chooseQuestion ({
posts: recovered.eligiblePosts.length > 1
? recovered.eligiblePosts
: availablePosts,
questions: recovered.scoringQuestions,
scores: recovered.scores,
answers,
askedIds,
gameSeed })
setWinningRunTargetId (nextWinningRunTargetId)
setWinningRunStartAnswerCount (nextWinningRunStartAnswerCount)
if (nextQuestion)
{
@@ -1442,7 +1780,7 @@ const GekanatorPage: FC = () => {
return
}
setActiveGuessId (guess?.id ?? null)
setActiveGuessId (bestPost (recoveredGuessablePosts, recovered.scores)?.id ?? null)
setPhase ('guess')
}
@@ -1496,12 +1834,13 @@ const GekanatorPage: FC = () => {
setExtraQuestions ([])
setExtraQuestionAnswers ({ })
setPhase ('extra_questions')
const nonce = createGameSeed ()
try
{
const questions = await queryClient.fetchQuery ({
queryKey: gekanatorKeys.extraQuestions (gameId),
queryFn: () => fetchGekanatorExtraQuestions (gameId) })
queryKey: gekanatorKeys.extraQuestions (gameId, nonce),
queryFn: () => fetchGekanatorExtraQuestions (gameId, nonce) })
setExtraQuestions (questions)
setExtraQuestionState (questions.length > 0 ? 'ready' : 'empty')
}
@@ -1556,6 +1895,39 @@ const GekanatorPage: FC = () => {
&& !(error)
&& !(acceptedQuestionsError)
useEffect (() => {
if (
phase !== 'question'
|| isLoading
|| acceptedQuestionsLoading
)
return
const winningRunFinished =
winningRunTargetId !== null
&& winningRunStartAnswerCount !== null
&& winningRunQuestionCount (answers, winningRunStartAnswerCount) >= winningRunQuestionLimit
&& eligiblePosts.length === 1
&& eligiblePosts[0]?.id === winningRunTargetId
const nextGuess = displayedGuess ?? guess
if (currentQuestion || (!(winningRunFinished) && !(nextGuess)))
return
setActiveGuessId ((winningRunFinished ? guess : nextGuess)?.id ?? null)
setLastGuessQuestionCount (answers.length)
setPhase ('guess')
}, [
phase,
currentQuestion,
guess,
displayedGuess,
answers,
eligiblePosts,
winningRunTargetId,
winningRunStartAnswerCount,
isLoading,
acceptedQuestionsLoading])
return (
<MainArea className="bg-yellow-50 dark:bg-red-975">
<Helmet>
@@ -1662,24 +2034,6 @@ const GekanatorPage: FC = () => {
</div>
</div>)}
{!(isLoading) && phase === 'question' && !(currentQuestion) && (
<div className="space-y-4">
<p className="text-xl font-bold">
</p>
<button
type="button"
className="rounded border border-yellow-300 px-4 py-2
hover:bg-yellow-100 dark:border-red-700
dark:hover:bg-red-900"
onClick={() => {
setActiveGuessId (guess?.id ?? null)
setPhase ('guess')
}}>
</button>
</div>)}
{phase === 'guess' && displayedGuess && (
<div className="space-y-4">
<p className="text-xl font-bold">?</p>